$contents = file_get_contents('http://www.yellowpages.com.iq/ajax/get/register/Categories.php');
$data = JSON_decode($contents);
$excel_file = fopen("file.csv", "a+");
$table = "<table border='1'>";
foreach($data as $elem) {
$table .= "<tr>";
foreach($elem as $key => $prop) {
$table .= "<th>$key</th>";
$table .= "<td>$prop</td>";
fwrite($excel_file, "$key,$prop\n");
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;
但问题是,它是否需要数据并正确显示,尽管它倾向于将其格式化为:
身份1
类别广告
身份2
类别农业&amp; FoodÂ
身份3
类别空调
id 4
类别航空公司
id 5
铝和铝玻璃
答案 0 :(得分:1)
您可以使用fputcsv
更改代码,该代码会处理双引号并转义它们。
为此您需要将JSON作为关联数组(提供第二个参数true
):
$data = JSON_decode($contents, true);
然后你所拥有的循环将替换为:
// "loop" for the header (only 1 iteration)
foreach($data as $elem) {
$table .= "<tr><th>" . implode("</th><th>", array_keys($elem)) . "</th></tr>";
fputcsv($excel_file, array_keys($elem));
break; // only need one row for header
}
// Restart loop for the data
foreach($data as $elem) {
$table .= "<tr><td>" . implode("</td><td>", $elem) . "</td></tr>";
fputcsv($excel_file, $elem);
}