json 在php中读取一个文本文件并提取一些元素[duplicate]

zpjtge22  于 2023-02-26  发布在  PHP
关注(0)|答案(5)|浏览(116)
    • 此问题在此处已有答案**:

Extract JSON from HTML source and use it(1个答案)
How to extract and access data from JSON with PHP?(1个答案)
3天前关闭。
我有一个文本文件。我想读取该文件并从元素中获取一些数据。当我读取该文件时,它可能是返回字符串(我不确定)。该文件包含一些数据,如下所示:

Can we get Prism Cluster Mail in summarize way like below.  
----------------------------------------------------------------

{
   "Employees":[
      {
         "userId":"rirani",
         "jobTitleName":"Developer",
         "firstName":"Romin",
         "lastName":"Irani",
         "preferredFullName":"Romin Irani",
         "employeeCode":"E1",
         "region":"CA",
         "phoneNumber":"408-1234567",
         "emailAddress":"romin.k.irani@gmail.com"
      },
      {
         "userId":"nirani",
         "jobTitleName":"Developer",
         "firstName":"Neil",
         "lastName":"Irani",
         "preferredFullName":"Neil Irani",
         "employeeCode":"E2",
         "region":"CA",
         "phoneNumber":"408-1111111",
         "emailAddress":"neilrirani@gmail.com"
      },
      {
         "userId":"thanks",
         "jobTitleName":"Program Directory",
         "firstName":"Tom",
         "lastName":"Hanks",
         "preferredFullName":"Tom Hanks",
         "employeeCode":"E3",
         "region":"CA",
         "phoneNumber":"408-2222222",
         "emailAddress":"tomhanks@gmail.com"
      }
   ]
}

Best Regards
The Team

我想提取用户名,职位名称和电话号码。我该怎么做呢?我是一个新的php。我已经尝试了以下代码。但它不能正常工作。有人能帮忙吗?

header('Content-type: application/json');   
    $data = preg_split("/\r\n/", file_get_contents("cluster.txt")); 
    $dt= json_encode($data, JSON_UNESCAPED_SLASHES);
    $final_dt=stripslashes($dt);
    $final_dt_arr=json_decode($final_dt,true);
    //echo "<pre>"; print_r($final_dt_arr);
    echo $final_dt;
4dc9hkyq

4dc9hkyq1#

我看了一下上面的脚本,你已经使用了json_decode,这是一个很好的开始。你能试试下面的代码(我的大多数项目)使用它吗:

// Read the JSON file into a string
$json_string = file_get_contents('urjsonfile.json');

// Decode the JSON string into a PHP object
$data = json_decode($json_string);

// Extract the desired data from the object
foreach ($data->Employees as $employee) {
    $userId = $employee->userId;
    $jobTitleName = $employee->jobTitleName;
    $phoneNumber = $employee->phoneNumber;

    // Do something with the extracted data, such as print it out
    echo "User ID: $userId, Job Title: $jobTitleName, Phone Number: $phoneNumber\n";
}
  1. file_get_contents()函数将JSON文件读入字符串
    1.使用json_decode()解码为PHP对象
  2. foreach循环然后迭代对象中Employees数组的每个元素,提取所需的数据。
    也可以将第二个参数作为true传递,以返回一个关联数组。
oxiaedzo

oxiaedzo2#

到目前为止我已经理解了你的问题。我已经分享了我的答案。希望它可能会有帮助。
如果仍然不工作。请提供一个代码沙盒的例子
按你方要求

    • 菲律宾**
header('Content-type: application/json');   
// $data = preg_split("/\r\n/", file_get_contents("cluster.txt")); 
$data = file_get_contents("cluster.txt"); 
$_arrdata = json_decode($data, true);

foreach( $_arrdata['Employees'] as $key=>$cluster ){
  echo "userId: ".$cluster['userId'] ."jobTitleName: ".$cluster['jobTitleName']. "phoneNumber". $cluster['phoneNumber']."\n";
}

此外,如果您希望将其存储在数组中以备将来使用,您也可以尝试以下操作。

    • 菲律宾**
header('Content-type: application/json');   
// $data = preg_split("/\r\n/", file_get_contents("cluster.txt")); 
$data = file_get_contents("cluster.txt"); 
$_arrdata = json_decode($data, true);

$result_array = [];
foreach( $_arrdata['Employees'] as $key=>$cluster ){
  $result_array[$key]['userId'] = $cluster['userId'];
  $result_array[$key]['jobTitleName'] = $cluster['jobTitleName'];
  $result_array[$key]['phoneNumber'] = $cluster['phoneNumber'];
}

print_r($result_array);

输出将如下所示。

Array
(
    [0] => Array
        (
            [userId] => rirani
            [jobTitleName] => Developer
            [phoneNumber] => 408-1234567
        )

    [1] => Array
        (
            [userId] => nirani
            [jobTitleName] => Developer
            [phoneNumber] => 408-1111111
        )

    [2] => Array
        (
            [userId] => thanks
            [jobTitleName] => Program Directory
            [phoneNumber] => 408-2222222
        )

)
mxg2im7a

mxg2im7a3#

@Lia,首先你将从你的字符串中只选择json数据,然后你将转换为数组。

$str_data = file_get_contents("cluster.txt"); 
        if (strpos($str_data, '{') !== false) {
            $str_data = str_split($str_data);
            // extract the json message.
            $json = '';
            $in = 0;
            foreach ($str_data as $i => $char) {
                if ($char == '{') {
                    $in++;
                }
                if ($in) {
                    $json .= $str_data[$i];
                }
                if ($char == '}') {
                    $in--;
                }
            }
            if ($json) {
                $json = json_decode($json);
            }
            
            $array = json_decode(json_encode($json), true);
            echo "<pre>"; print_r($array);
            // now chill with your array
        }
mzaanser

mzaanser4#

如果文件的开头和结尾总是正好有3行非JSON内容,则可以在尝试解码之前从数据中删除无关内容,然后继续解码并以通常的方式使用JSON数据。
例如:

$file_data = file_get_contents("cluster.txt"); 

//get file data into an array and remove first 3 lines
$file_data_arr = explode("\n", $file_data);
$file_data_arr = array_slice($file_data_arr, 3);

//Now remove last 3 lines and convert back to a string
array_splice($file_data_arr, -3);
$json_string = implode("\n", $file_data_arr);

// Decode the JSON string into a PHP object
$data = json_decode($json_string);

// Extract the desired data from the object
foreach ($data->Employees as $employee) {
    $userId = $employee->userId;
    $jobTitleName = $employee->jobTitleName;
    $phoneNumber = $employee->phoneNumber;

    // Do something with the extracted data, such as print it out
    echo "User ID: $userId, Job Title: $jobTitleName, Phone Number: $phoneNumber\n";
}

工作演示:https://3v4l.org/Ar7ne

sdnqo3pr

sdnqo3pr5#

好吧,当我看到所有关于这个文本和JSON混合在一起的糟糕文件内容的评论时,我认为你唯一能做的就是尝试只提取文件的JSON部分,它位于左括号和右括号之间({ ... })。
这可以在正则表达式的帮助下完成。这显然不是很安全,因为周围的文本也可能有这些字符。我们会说情况不是这样的...
简单的正则表达式为/\{.*\}/s
但是我们可以稍微改进一下,因为我们知道它应该包含Employees条目,如果文件的其余部分在注解中也有一些大括号,这会有所帮助,正则表达式将变为:

/\{\s*"Employees"\s*:\s*\[.*\]\s*\}/su

要用蹩脚的内容测试它并获得模式的解释:https://regex101.com/r/wPGwIk/1
完整的PHP代码:

<?php

// $input_data = file_get_contents('cluster.txt');

// The crapy file content with the JSON inside it.
$input_data = <<<END_OF_FILE
Can we get Prism Cluster Mail in summarize way like below. {dummy}
----------------------------------------------------------------

{
   "Employees":[
      {
         "userId":"rirani",
         "jobTitleName":"Developer",
         "firstName":"Romin",
         "lastName":"Irani",
         "preferredFullName":"Romin Irani",
         "employeeCode":"E1",
         "region":"CA",
         "phoneNumber":"408-1234567",
         "emailAddress":"romin.k.irani@gmail.com"
      },
      {
         "userId":"nirani",
         "jobTitleName":"Developer",
         "firstName":"Neil",
         "lastName":"Irani",
         "preferredFullName":"Neil Irani",
         "employeeCode":"E2",
         "region":"CA",
         "phoneNumber":"408-1111111",
         "emailAddress":"neilrirani@gmail.com"
      },
      {
         "userId":"thanks",
         "jobTitleName":"Program Directory",
         "firstName":"Tom",
         "lastName":"Hanks",
         "preferredFullName":"Tom Hanks",
         "employeeCode":"E3",
         "region":"CA",
         "phoneNumber":"408-2222222",
         "emailAddress":"tomhanks@gmail.com"
      }
   ]
}

Best Regards
~{ The Team }~
END_OF_FILE;

// Extract the JSON which should have the "Employees" entry.
if (preg_match('/\{\s*"Employees"\s*:\s*\[.*\]\s*\}/su', $input_data, $matches)) {
    $data = json_decode($matches[0]);
    
    if ($error = json_last_error()) {
        print "Could not decode the JSON string!\n";
        exit(2);
    }
    
    print "userId\tjobTitleName\tphoneNumber\n";
    print "-----------------------------------\n";
    foreach ($data->Employees as $id => $employee) {
        print "$employee->userId\t$employee->jobTitleName\t$employee->phoneNumber\n";
    }
}
else {
    print "No JSON found!\n";
    exit(1);
}

执行输出:

userId  jobTitleName    phoneNumber
-----------------------------------
rirani  Developer   408-1234567
nirani  Developer   408-1111111
thanks  Program Directory   408-2222222

您可以在这里运行它:https://onlinephp.io/c/5386c

相关问题