简体   繁体   English

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

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

I have json file having content like this : 我有具有这样的内容的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, "
    }
  }]

Right now to read first record i am using file_get_contents get complete data and then parsing into array. 现在要读取第一条记录,我正在使用file_get_contents获取完整的数据,然后解析为数组。 I want to fetch only first record without getting whole file content in memory using php. 我只想获取第一条记录,而不会使用php在内存中获取整个文件的内容。 Is there any way to do this ? 有什么办法吗?

Many Thanks, M. 非常感谢,M。

This is a hack but if you know the JSON structure. 这是一个hack,但是如果您知道JSON结构。 Anyway }, may not occur in the first record. 无论如何},可能不会出现在第一条记录中。

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

If you do not want to read the whole JSON file you could do something like this (adjust to your needs!): 如果您不想读取整个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];

Anway everything which I just suggested here is usually not recommendable (in 99% of the use cases) . 通常不建议我在这里提出的所有建议(在99%的用例中) Maybe you have to adapt this code a bit and also it will not work for minified JSON. 也许您需要稍微修改一下此代码,并且对于缩小的JSON也将不起作用。

Better you parse the whole file and go ahead. 最好您分析整个文件然后继续。

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

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