Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

php - How to get JSON in response

When I debug a site via Chrome browser I get JSON response. But when I try to do this via PHP I get an error message.

failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found

Thanks for any help.

For example:

Things to do in Chrome:

Go to page: http://gruper.pl/warszawa and on the bottom you will see a button "Wiecej ofert". After click you will see in a debug:

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

and response:

[{"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".....

Is there any possibility to get the same in PHP?

My code is:

<?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
" .
                      "Accept:application/json
" .
                      "Accept-Encoding:gzip,deflate,sdch
" .
                      "X-Requested-With:XMLHttpRequest
",
        'method'  => 'GET'
    ),
);

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

?>
<html>

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

</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like that URL will return a 404 HTTP status code unless these headers are set:

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

So this will work:

<?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
" .
                    "Referer: http://gruper.pl/warszawa"
    )
);

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

echo $result;

?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...