尝试使用cURL解析JSON - var_dump返回NULL

时间:2016-03-15 04:32:24

标签: php json curl

我试图从下面的URL解析JSON。但是,当我运行var_dump(json_decode($result, true))时,它返回NULL。但是当我从echo $item_url复制URL时,它会返回正确的JSON。

我读过的另一个问题是var_dump(json_decode($result, true));返回一个带空格的字符串,这可能是一个问题

$item_url = "http://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid=730&market_hash_name=" . $rgDescriptions->market_hash_name;

echo $item_url;

$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, urlencode($item_url));
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
$result = curl_exec($curl_handle);
curl_close($curl_handle);

var_dump(json_decode($result, true));

Bellow是可能传递的URL的示例。

http://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid=730&market_hash_name=AK-47%20|%20Aquamarine%20Revenge%20(Minimal%20Wear)

1 个答案:

答案 0 :(得分:1)

在更改代码中的一行后,它为我工作。我认为您只需要编码$rgDescriptions->market_hash_name而不是整个网址。

更改

curl_setopt($curl_handle, CURLOPT_URL, urlencode($item_url));

curl_setopt($curl_handle, CURLOPT_URL, $item_url);

完整代码

$item_url = "http://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid=730&market_hash_name=AK-47%20|%20Aquamarine%20Revenge%20(Minimal%20Wear)";

$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $item_url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
$result = curl_exec($curl_handle);
curl_close($curl_handle);

var_dump(json_decode($result, true));

<强>输出:

array(4) {
  ["success"]=>
  bool(true)
  ["lowest_price"]=>
  string(6) "$26.38"
  ["volume"]=>
  string(3) "133"
  ["median_price"]=>
  string(6) "$26.35"
}