iT邦幫忙

1

PHP 如何讀取遠端json 中資料並解析取得其中一項

想抓疾管確診資料(這是json沒錯吧...XD:
https://covid19dashboard.cdc.gov.tw/dash3
求各位大神解答
/images/emoticon/emoticon02.gif

淺水員 iT邦大師 6 級 ‧ 2020-07-29 17:46:37 檢舉
你可能要說清楚一點是哪邊有問題喔,不然只能回你「就直接抓阿」
淺水員 iT邦大師 6 級 ‧ 2020-07-29 18:14:58 檢舉
php 可用 curl:https://blog.johnsonlu.org/php-curl/

javascript 可用
XmlHttpRequest:https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

fetch:https://developer.mozilla.org/zh-TW/docs/Web/API/Fetch_API/Using_Fetch
QR摳 iT邦新手 5 級 ‧ 2020-07-29 23:00:10 檢舉
最後是不小心寫成printf...
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
dragonH
iT邦超人 5 級 ‧ 2020-07-29 21:10:33
最佳解答

code

<?php
    $url = "https://covid19dashboard.cdc.gov.tw/dash3";
    $resutlt1 = file_get_contents($url);
    $resutlt1_json = json_decode($resutlt1, true);
    print_r("確診: ".$resutlt1_json[0]["確診"]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result2 = curl_exec($ch);
    $result2_json = json_decode($result2, true);
    print_r("\n送驗: ".$result2_json[0]["送驗"]);
    curl_close($ch);

result

確診: 467
送驗: 81,167

兩種方法自己挑

淺水員 iT邦大師 6 級 ‧ 2020-07-29 21:15:51 檢舉

記得 file_get_contents 能不能抓網頁資料跟 PHP 設定有關。

dragonH iT邦超人 5 級 ‧ 2020-07-29 21:22:34 檢舉

/images/emoticon/emoticon12.gif

QR摳 iT邦新手 5 級 ‧ 2020-07-29 22:57:07 檢舉

我發現是C語言後遺症...
寫成printf...
/images/emoticon/emoticon04.gif

1
打狗松鼠
iT邦新手 4 級 ‧ 2020-07-29 18:01:09

明明問問題簡潔有力,怎麼就不會敘述問題...

https://lmgtfy.com/?q=php+get+web+api+json

看更多先前的回應...收起先前的回應...

另外,其實這種事情更多時候會交給JavaScript去做(關鍵字:Ajax),不過如果對方API會遇到同源政策問題的話就回歸到Server端處理吧

QR摳 iT邦新手 5 級 ‧ 2020-07-29 22:59:21 檢舉

感謝您的意見,最後只是C語言後遺症 = =
寫成printf了啊啊啊~~

居然是這樣嗎XDD
這時候每份語言都準備一份memo果然很好用

QR摳 iT邦新手 5 級 ‧ 2020-07-30 21:21:42 檢舉

感謝建議XD

1
r567tw
iT邦研究生 5 級 ‧ 2020-07-29 21:14:58
<?php
$data = file_get_contents('https://covid19dashboard.cdc.gov.tw/dash3');
print_r(json_decode($data,true));
// output: Array ( [0] => Array ( [確診] => 467 [解除隔離] => 441 [死亡] => 7 [送驗] => 81,167 [排除] => 80,105 [昨日確診] => 5 [昨日排除] => 320 [昨日送驗] => 344 ) )

如果你還問我說要怎麼處理 array 的資料的話....
請好好修習PHP吧!

看更多先前的回應...收起先前的回應...
QR摳 iT邦新手 5 級 ‧ 2020-07-29 22:54:50 檢舉

當然不是...請不要小看國1生

r567tw iT邦研究生 5 級 ‧ 2020-07-30 10:10:55 檢舉

沒有這個意思啦! 原來只是C 語言後遺症阿~ 沒關係 經驗多了 就會越來越好 未來潛力無窮~

QR摳 iT邦新手 5 級 ‧ 2020-07-30 21:22:18 檢舉

哦~

QR摳 iT邦新手 5 級 ‧ 2020-07-30 21:22:47 檢舉

感謝鼓勵

我要發表回答

立即登入回答