2016-03-08 50 views
1

我試着使用如下因素代碼從一個網站的數據:充分利用網站JSON數據返回「字符串(0)」

<?php 
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798'; 
$content = file_get_contents($url); 
var_dump($content); 
$json = json_decode($content, true); 

var_dump($json); 

for ($idx = 0; $idx < count($json); $idx++) { 
$obj = (Array)$json[$idx]; 
echo 'result' . $obj["name"]; 
} 
?> 

至極就是讓我這樣的結果: http://take.ms/4PzZM

+0

什麼的var_dump($內容)的結果?您還可以使用json_last_error()和json_last_error_msg()來調試解碼json的問題。 –

+0

$ content是來自$ url的數據並返回String(0) –

回答

0

有json中沒有數字鍵從您在問題中發佈的網址返回。因此,用數字鍵遍歷關聯數組不會返回任何結果。

這是你正在使用的JSON的結構:

{ 
    "item": { 
    "icon": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_sprite.gif?id=4798", 
    "icon_large": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_big.gif?id=4798", 
    "id": 4798, 
    "type": "Default", 
    "typeIcon": "http://www.runescape.com/img/categories/Default", 
    "name": "Adamant brutal", 
    "description": "Blunt adamantite arrow... ouch.", 
    "current": { 
     "trend": "neutral", 
     "price": 529 
    }, 
    "today": { 
     "trend": "neutral", 
     "price": 0 
    }, 
    "members": "true", 
    "day30": { 
     "trend": "negative", 
     "change": "-9.0%" 
    }, 
    "day90": { 
     "trend": "negative", 
     "change": "-20.0%" 
    }, 
    "day180": { 
     "trend": "negative", 
     "change": "-31.0%" 
    } 
    } 
} 

嘗試訪問$json["item"]。這應該給你一些更有意義的工作。如果你想遍歷在項目的鍵/值對,使用foreach循環:

foreach($json["item"] as $key => $value) { 
    echo $key . ":"; 
    print_r($value); 
} 
0
<?php 
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798'; 
$content = file_get_contents($url); 
echo "<pre>"; 
//print_r($content); 
$data = json_decode($content); 
print_r($data); //Show the json decoded data comes form $url 

##Parse this array {$data} using foreach loop as your use 
?>