这是我想通过PHP脚本运行的JSON代码:
{"source":"URl","title":"New title","created":"date","id":"xxxxx","comments":[{"id":"xxxx","imported_display_name":"xxxx","body_html":"xxxxx","imported_email":"xxxxx","parent_id":"xxxx"}]},{"source":"URl","title":"New title","created":"date","id":"xxxxx","comments":[{"id":"xxxx","imported_display_name":"xxxx","body_html":"xxxxx","imported_email":"xxxxx","parent_id":"xxxx"}]}
我想要JSON数据,如。
{"source":"URl","title":"New title","created":"date","id":"xxxxx","comments":[{"id":"xxxx","imported_display_name":"xxxx","body_html":"xxxxx","imported_email":"xxxxx","parent_id":"xxxx"}]}
{"source":"URl","title":"New title","created":"date","id":"xxxxx","comments":[{"id":"xxxx","imported_display_name":"xxxx","body_html":"xxxxx","imported_email":"xxxxx","parent_id":"xxxx"}]}
表示每个源都以新行开头,并且它们之间没有逗号。 这是我的PHP代码,它提供了JSON文件。
$p=0;
array_push($result_comments,$result);
$fp = fopen($p.'_results.json', 'w');
fwrite($fp, json_encode(utf8ize($result_comments)));
fclose($fp);
$p ++;
这是功能
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
请建议我可以通过php脚本的修改获得所需的json数据。或者我必须手动删除它。
答案 0 :(得分:0)
您可以尝试以下内容。 Json对每一行进行编码并将其添加到$result_comments
数组中。最后用换行符破坏这个数组并将其写入文件:($data
你给json作为php数组)
$data = array (
0 =>
array (
'source' => 'URl',
'title' => 'New title',
'created' => 'date',
'id' => 'xxxxx',
'comments' =>
array (
0 =>
array (
'id' => 'xxxx',
'imported_display_name' => 'xxxx',
'body_html' => 'xxxxx',
'imported_email' => 'xxxxx',
'parent_id' => 'xxxx',
),
),
),
1 =>
array (
'source' => 'URl',
'title' => 'New title',
'created' => 'date',
'id' => 'xxxxx',
'comments' =>
array (
0 =>
array (
'id' => 'xxxx',
'imported_display_name' => 'xxxx',
'body_html' => 'xxxxx',
'imported_email' => 'xxxxx',
'parent_id' => 'xxxx',
),
),
),
);
$result_comments = array();
foreach($data as $result){
$result_comments[] = json_encode(utf8ize($result));
}
file_put_contents('results.json',implode(PHP_EOL,$result_comments));
// result.json
// {"source":"URl","title":"New title","created":"date","id":"xxxxx","comments":[{"id":"xxxx","imported_display_name":"xxxx","body_html":"xxxxx","imported_email":"xxxxx","parent_id":"xxxx"}]}
// {"source":"URl","title":"New title","created":"date","id":"xxxxx","comments":[{"id":"xxxx","imported_display_name":"xxxx","body_html":"xxxxx","imported_email":"xxxxx","parent_id":"xxxx"}]}