简体   繁体   中英

PHP JSON response is not loading from URL

Here's the link that provides JSON response: https://www.instagram.com/p/CDq1KJPJcTN/?__a=1

Simple copy and paste the URL in browser gives JSON response. But When I try to access the same in PHP using file_get_contents or cURL, it's showing Instagram's html page code

ini_set("allow_url_fopen", 1);
ini_set("allow_url_include", 1);

$context = [
            'http' => [
                    'method' => 'GET',
                    'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36',
                ],
            ];
$context = stream_context_create($context);
$data = file_get_contents('https://www.instagram.com/p/CDq1KJPJcTN/?__a=1', false, $context);

cURL:

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.instagram.com/p/CDq1KJPJcTN/?__a=1');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36');
$query = curl_exec($curl_handle);
curl_close($curl_handle);
echo $query;

When I use rest api test tool ( https://resttesttest.com/ ). It's giving JSON response only. I think some important header is missing, which I'm unable to figure out. Content-Type:application/json & Access-Control-Allow-Origin: * are given.

Try this

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.instagram.com/p/CDq1KJPJcTN/?__a=1');
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_handle, CURLOPT_HEADER, FALSE);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36');
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);

$query = curl_exec($curl_handle);
curl_close($curl_handle);

echo $query;

Using file_get_contents worked for me in local

ini_set("allow_url_fopen", TRUE);
ini_set("allow_url_include", TRUE);

$context = [
            'http' => [
                    'method' => 'GET',
                    'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36',
                ],
            ];
$context = stream_context_create($context);
$data = file_get_contents('https://www.instagram.com/p/CDq1KJPJcTN/?__a=1', false, $context);
echo $data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM