猿问

从JSON数组中获取数据-PHP

我有一个名为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);

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


有只小跳蛙
浏览 189回答 1
1回答

陪伴而非守候

您将使用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);演示版
随时随地看视频慕课网APP
我要回答