想要詢問前輩,我用的是PHP, 想用這個open data json 讀取, 可是一直顯示錯誤『Warning: Invalid argument supplied for foreach()』,我想要知道我的程式碼是錯在哪裡,能否請前輩提點。
Json的網址:https://gis.taiwan.net.tw/XMLReleaseALL_public/hotel_C_f.json
我的php程式碼:
<?php
$handle = fopen("https://gis.taiwan.net.tw/XMLReleaseALL_public/hotel_C_f.json","rb");
$content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode($content,true);
foreach($content['XML_Head']['Info'] as $locate){
echo $locate;
}
?>
有兩個原因
程式錯誤:$content['XML_Head']['Info']
要改成 $content['XML_Head']['Infos']
資料編碼:網站上的 json 編碼是 UTF-8 with BOM 以致 json_decode 失敗,解決方法是用substr($content,3)
刪掉頭三個字元使成為 UTF-8 即可正常 decode
修正後程式如下
<?php
$handle = fopen("https://gis.taiwan.net.tw/XMLReleaseALL_public/hotel_C_f.json","rb");
$content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode(substr($content,3),true);
foreach($content['XML_Head']['Infos']['Info'] as $locate){
echo $locate['Id']." ".$locate['Name']."\n";
}
?>