从网站获取 JSON 数据返回 “ string(0) ”


Getting JSON data from website returns " string(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"];
}
?>

这让我得到了这个结果:

字符串(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  
?>

从您在问题中发布的 URL 返回的 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);
}