Getting error : 'Trying to get property 'graphql' of non-object in ' for PHP script

106 Views Asked by At

I'm trying to create an Instagram media downloader where I'm using the following code but it's giving me this error. Can someone tell me where am I wrong? I'm stuck in this since last 6-7 hrs.

The error says -

Notice: Trying to get property 'graphql' of non-object in C:\xampp\htdocs\proj-2\index.php on line 13

Notice: Trying to get property 'shortcode_media' of non-object in C:\xampp\htdocs\proj-2\index.php on line 13

Notice: Trying to get property 'display_resources' of non-object in C:\xampp\htdocs\proj-2\index.php on line 13

Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\proj-2\index.php on line 18

index.php

<?php
$html = "";

//Getting Json File From URL?__a=1
if(isset($_GET['url'])) {
    $json = file_get_contents($_GET['url']."?__a=1");
    //Getting the file content
    $json = json_decode($json);
    //Converting the JSON into Php object

    $arr = $json->graphql->shortcode_media->display_resources;


    for($i=0;$i<count($arr);$i++ ) {
        $html .= '<img src="'.$arr[$i]->src.'" > <br><br> <a href="'.$arr[$i]->src.'" download >Download</a><hr>';
    }
}

?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instagram Photo Downloader</title>
</head>
<body>
    <h1>Instagram Downloader</h1>
    <form action="" method="get">
    <input type="text" name="url" id="">
    <button type="submit">DOWNLOAD</button>
    </form>

    <div class="image">
    <?php echo $html ; //Showing all Stored Images ?>
    </div>
</body>
</html>

Where is thing going wrong? What's the error in that Line 13?


Edit 1:

Updated my code to following in Line 13:

$arr = $json['graphql']['shortcode_media']['display_resources'];

Still getting another warning -

Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\proj-2\index.php on line 16
1

There are 1 best solutions below

3
hNczy On

Possibly there is a json_decode() error because the parameter is not a valid JSON string. You can check the decoding success with the json_last_error().

I hope this code snippet will help:

$json = json_decode($json);
if (JSON_ERROR_NONE !== json_last_error()) {
    throw new Exception('json_decode failed: ' . json_last_error_msg());
}