如何获得JSON作为回应

时间:2014-02-24 12:11:38

标签: php

当我通过Chrome浏览器调试网站时,我获得了JSON响应。但是当我尝试通过PHP执行此操作时,我收到错误消息。

  

无法打开流:HTTP请求失败!找不到HTTP / 1.0 404

感谢您的帮助。

例如:

Chrome中可以做的事情:

转到页面:http://gruper.pl/warszawa,在底部你会看到一个按钮“Wiecej ofert”。点击后,您将在调试中看到:

http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1

并回复:

[{"ID_PAGE":"59199","ID_CITY":"3952","main_city":"3952","date_start":"2014-02-23 18:00:00","date_end":"2014-03-01 23:59:00","price".....

是否有可能在PHP中获得相同的内容?

我的代码是:

<?php

$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  =>  "Content-type: application/x-www-form-urlencoded\r\n" .
                      "Accept:application/json\r\n" .
                      "Accept-Encoding:gzip,deflate,sdch\r\n" .
                      "X-Requested-With:XMLHttpRequest\r\n",
        'method'  => 'GET'
    ),
);

$context  = stream_context_create($options);
$result = (file_get_contents($url, false, $context));

?>
<html>

<head>
<meta charset="UTF-8">
</head> 

</html>

1 个答案:

答案 0 :(得分:1)

看起来该URL将返回404 HTTP状态代码,除非设置了这些标头:

X-Requested-With: XMLHttpRequest
Referer: http://gruper.pl/warszawa

所以这会奏效:

<?php

$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header' => "X-Requested-With: XMLHttpRequest\r\n" .
                    "Referer: http://gruper.pl/warszawa"
    )
);

$context  = stream_context_create($options);
$result = (file_get_contents($url, false, $context));

echo $result;

?>