iT邦幫忙

0

php- json的問題

想要詢問前輩,我用的是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']['Info']
沒實際測過
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-11-25 12:10:31
最佳解答

有兩個原因
程式錯誤:$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";
    }
?>

我想要再請問一下,您有說要『刪掉頭三個字元』,能不能請跟我說是刪掉哪3個字元? 不好意思。 謝謝

froce iT邦大師 1 級 ‧ 2021-11-25 13:30:53 檢舉

非常謝謝前輩們的提點!!

我要發表回答

立即登入回答