使用PHP从网页获取json数据

时间:2015-08-20 22:30:40

标签: php json curl steam-web-api

我正在尝试从here (example url)获取回复,首先,我认为我应该使用file_get_contents()

当我尝试这个时,我收到以下错误:

$(document).on('loaded.bs.modal', '.modal', function(){
    $(window).trigger('resize');
});

我知道这是因为它正在转换&到Warning: file_get_contents(https://steamcommunity.com/market/pricehistory/?country=US&currency=1&appid=730&market_hash_name=SG%20553%20|%20Damascus%20Steel%20(Factory%20New)): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 。我已经尝试了很多方法来解决这个问题,但是他们都失败了,在快速谷歌之后我得出结论,file_get_contents()转换为&

我的下一步是尝试卷曲。我先尝试了下面的代码:

&

但是这返回了&作为回复。我想知道这是否与json编码有关,所以我尝试通过json_decode()但它没有用。

接下来,我试过了:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
   CURLOPT_RETURNTRANSFER => 1,
   CURLOPT_URL => 'http://steamcommunity.com/market/pricehistory/?country=US&currency=1&appid=730&market_hash_name='.$hash,
   CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

但又得到了回复‹ŠŽÿÿ)»L

这个回复意味着什么,我可以解析它吗?如果没有,我该如何正确获取此数据?此外,为什么file_get_contents()没有工作?

3 个答案:

答案 0 :(得分:3)

我很确定这种情况正在发生,因为您需要某种类型的访问令牌来访问Steam Web API。

请参阅SO上的this answer

基本上,Steam正在使用" 400 Bad Request"状态。但是,通过执行以下操作可以忽略此错误:

<?php
    $url = "https://steamcommunity.com/market/pricehistory/?country=US&currency=1&appid=730&market_hash_name=SG%20553%20%7C%20Damascus%20Steel%20(Factory%20New)";
    $context = stream_context_create(array(
      'http' => array(
          'ignore_errors'=>true,
          'method'=>'GET'
          // for more options check http://www.php.net/manual/en/context.http.php
        )
    ));
    $response = file_get_contents($url, false, $context);
    echo $response; // returns "[]"
?>

请务必在SO上查看this answer

答案 1 :(得分:1)

可能是你的回复是gzip,尝试使用CURLOPT_ENCODING。

curl_setopt($curl ,CURLOPT_ENCODING, '')

如果您使用https,请不要忘记禁用CURLOPT_SSL_VERIFYPEER。

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false)

有一件事,如果我跟随您的浏览器链接并打开我的调试控制台。 我看到你的请求有400状态代码(错误请求)。

enter image description here

答案 2 :(得分:0)

我无法说出您的观点,但您可以使用urlencode()来解决您的错误请求错误:

$url = urlencode('https://steamcommunity.com/market/pricehistory/?country=US&currency=1&appid=730&market_hash_name=SG%20553%20%7C%20Damascus%20Steel%20(Factory%20New))'
file_get_contencts($url);