我想抓取上方這張圖裡面的資料
有上網查一些資訊.但是怎麼改echo不出資料
不然就是出現錯誤..想請問該怎麼foreach...
附上程式碼,也是參考版上其他大大的程式
header('Content-Type: text/html; charset=utf-8');
$handle = fopen("https://data.ntpc.gov.tw/api/datasets/ACCE802D-58CC-4DFF-9E7A-9ECC517F78BE/json/preview","rb");
$content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode($content,true);
foreach($content as $key => $locate)
{
echo $key;
}
$handle = fopen("https://data.ntpc.gov.tw/api/datasets/ACCE802D-58CC-4DFF-9E7A-9ECC517F78BE/json/preview","rb");
$content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode($content);
foreach($content as $element) {
foreach($element as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
}
因為他的json是用陣列包起來的
所以需要逐一拆解
$data = json_decode($response);
然後再抓陣列資料做運用
如果只是get的話
$url = 'https://data.ntpc.gov.tw/api/datasets/ACCE802D-58CC-4DFF-9E7A-9ECC517F78BE/json/preview';
$json = file_get_contents($url);
var_dump(json_decode($json));
<?php
header('Content-Type: text/html; charset=utf-8');
$handle = fopen("https://data.ntpc.gov.tw/api/datasets/ACCE802D-58CC-4DFF-9E7A-9ECC517F78BE/json/preview","rb");
$content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode($content,true);
//資料看起來有兩層,第一層沒有KEY所以不用顯示,第二層用列舉的,把 KEY 跟 VALUE並排即可,以下用ul li排版
foreach($content as $key => $locate)
{
echo "<ul>";
foreach($locate as $k2 => $v2)
{
echo "<li>$k2 => $v2</li>";
}
echo "</ul>";
}
?>