curl not returning JSON data as expected

Viewed 47

I have the following code, where i am basically just doing a curl request to get the JSON data back.. the URL to the request should be:

 https://www.instagram.com/reel/CiAbVWmpiWR/?__a=1&__d=dis

so even if i just copy and paste the link above into the browser i can see the JSON data, however when putting it into code and requesting via CURL.. it just returns Oops an error occured.. what am i doing wrong ?

$mediaUrl = 'https://www.instagram.com/reel/CiAbVWmpiWR';
$pos = strpos($mediaUrl, '?');
if ($pos) {
    $mediaUrl = substr($mediaUrl, 0, $pos);
}
$url = rtrim($mediaUrl, '/') . '/?__a=1&__d=dis';

//var_dump($url);

$proxy = '139.99.54.49:10163';
$proxyauth = 'aditya:xcQWzyfX7ybNM8d';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);     // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);   // Use if proxy have username and password
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json') );
$data = curl_exec($ch);
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    var_dump($error_msg);
}


$json_data = json_decode($data, true);
var_dump($data);

so var_dump data returns

string(25) "Oops, an error occurred.

curl_errno($ch) is always NULL

UPDATE:

when the URL is not an instagram reel photo, just a regular photo like an example below:

https://www.instagram.com/p/CiPR10FhwZ6/?__a=1&__d=dis

the code above works perfectly fine

1 Answers

I think the API returned was in GraphQl Format. Can you please consider the following code and refer More on GrapQL API here

$mediaUrl = 'https://www.instagram.com/reel/CiAbVWmpiWR';
        $pos = strpos($mediaUrl, '?');
        if ($pos) {
            $mediaUrl = substr($mediaUrl, 0, $pos);
        }
        $url = rtrim($mediaUrl, '/') . '/?__a=1&__d=dis';
        $endpoint = $url;
        $query = "query {
  
            }";
        $data = array('query' => $query);
        $data = http_build_query($data);
        $options = array(
            'http' => array(
                'header' => "Content-Type: application/json\r\n".
                    "Content-Length: ".strlen($query)."\r\n".
                    "User-Agent:MyAgent/1.0\r\n",
                'method' => 'GET',
                'content' => $data
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($endpoint, false, $context);

        if ($result === FALSE) { /* Handle error */
        }
        print_r($result);
Related