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

时间:2017-07-28 15:35:27

标签: php json

我的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。

1 个答案:

答案 0 :(得分:1)

这是一个黑客,但如果你知道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];

Anway我在这里建议的所有内容通常都不推荐(在99%的用例中)。也许你必须稍微调整一下这个代码,它也不适用于缩小的JSON。

更好地解析整个文件并继续。

相关问题