我有一个名为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);
如何获取每个元素并将其输出到页面中?
答案 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);