从JSON数组中获取数据-PHP

时间:2019-04-27 19:26:42

标签: php json

我有一个名为test.txt的文本文件,其内容如下:

{"FirstName":"John","Title":"","Surname":"Smith"}
{"FirstName":"Daniel","Title":"","Surname":"Smith"}

我想在PHP脚本中循环浏览此JSON,因此最终输出是:

John Smith
Daniel Smith

我当前的PHP代码是:

$fn = fopen("./test.txt","r");
while(! feof($fn))  {
  $line = fgets($fn);
  // grab data from JSON
}
fclose($fn);

如何获取每个元素并将其输出到页面中?

1 个答案:

答案 0 :(得分:2)

您将使用json_decode()将该数据作为数组或对象(默认)。

JSON作为对象

$fn = fopen("./test.txt","r");
while(! feof($fn))  {
  $line = fgets($fn);
  $record = json_decode($line);
  echo $record->FirstName; // etc
}
fclose($fn);

JSON作为数组:

$fn = fopen("./test.txt","r");
while(! feof($fn))  {
  $line = fgets($fn);
  $record = json_decode($line, true);
  echo $record['FirstName']; // etc
}
fclose($fn);

Demo