繁体   English   中英

使用PHP从json文件中读取第一条记录

[英]Read first only record from json file using PHP

我有具有这样的内容的json文件:

[{
    "name" : "Mak",
    "registration_code" : "Registration code",
    "date" :"date",
    "time" : "time",
    "file_data" :{
        "Feature_0" : "0,0.956222737454317,"
    }
  },
  {
    "name" : "Andy",
    "date" :"date",
    "time" : "time",
    "file_data" :{
        "Feature_0" : "0,0.956222737454317, "
    }
  }]

现在要读取第一条记录,我正在使用file_get_contents获取完整的数据,然后解析为数组。 我只想获取第一条记录,而不会使用php在内存中获取整个文件的内容。 有什么办法吗?

非常感谢,M。

这是一个hack,但是如果您知道JSON结构。 无论如何},可能不会出现在第一条记录中。

$first = explode("},", $json_string, 2)[0];
$first .= "}]";
$obj = json_decode($first)[0];

如果您不想读取整个JSON文件,则可以执行以下操作(根据需要进行调整!):

         $content = "";
         $handle = fopen("json.file", "r"); if ($handle) {
         while (($line = fgets($handle)) !== false) {

                // with nested objects you have to count the occurrences of { and make sure it is the closer for the first object
                if (strpos($line, '},') !== false) {
                    break;
                } else {
                    $content .= $line;
                }
           }

           fclose($handle); 
        }  // proceed only with the lines read ...
        $content .= "}]";
        $obj = json_decode($content)[0];

通常不建议我在这里提出的所有建议(在99%的用例中) 也许您需要稍微修改一下此代码,并且对于缩小的JSON也将不起作用。

最好您分析整个文件然后继续。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM