我的代码:
$jsonarr = array('id' => '', 'source' => $source,
'time_date' => $timeunix, 'title' => $titler,
'description' => $description,
'link' => $linkr,'image' => $imageurl);
for ($x = 0; $x <= count($jsonarr); $x++) {
echo "The number is: $x <br>";
echo json_encode($jsonarr);
$fp = fopen('aaa.json', 'w');
fwrite($fp, json_encode($jsonarr));
fclose($fp);
}
输出即将到来
{"id":"","source":"BBC News - Politics","time_date":1422633420,"title":"'Train everyone' for digital world","description":"People everywhere need to adapt to a world being rapidly changed by digital technology, a leading academic says.","link":"http:\/\/www.bbc.co.uk\/news\/uk-wales-politics-31049769#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa","image":"http:\/\/news.bbcimg.co.uk\/media\/images\/80673000\/jpg\/_80673268_glasses_bbc.jpg"}
这是正确的,但我需要将所有项目添加到json而不仅仅是一个。
任何建议都将不胜感激。感谢
答案 0 :(得分:1)
创建一个字符串并将每个项目附加到字符串并将该字符串写入文件
$results = $db->query("SELECT * FROM table ORDER BY ID DESC");
$jsonString = '';
foreach ($results as $value) {
$id = '"ID":"'.trim($value['ID']).'"';
$artist = '"Artist":"'.trim($value['ArtistName']).'"';
$title = '"AlbumTitle":"'.trim($value['AlbumTitle']).'"';
$items = "\n\t{\n\t\t$id,\n\t\t$artist,\n\t\t$title\n\t},";
$jsonString = $jsonString .$items;
}
$jsonString = rtrim($jsonString,",");
file_put_contents("jsonfile.json", $jsonString);