Search code examples
phpjsoninstagraminstagram-api

Getting Instagram subscription JSON data from post in PHP


This whole process of subscriptions for the Instagram API seems to be less than straight forward.

I have some code set up to receive the post data sent when Instagram hits me with a notification of a post from one of my subscriptions. However when I try to view the data, the raw JSON, it posts I can't get at it. If I print_r or var_dump I just get the number 1.

See my code for accessing the data:

    // Catches realtime updates from Instagram
if ($_SERVER['REQUEST_METHOD']==='POST') {
     // Retrieves the POST data from Instagram
    $update = file_get_contents('php://input');
    $data = json_decode($update);

    var_dump($data); //Outputs 1
    print_r($data[0]); //Outputs 1

}   

How can I get at the JSON as an array?

This is what the JSON should look like:

[
    {
        "subscription_id": "1",
        "object": "user",
        "object_id": "1234",
        "changed_aspect": "media",
        "time": 1297286541
    },
    {
        "subscription_id": "2",
        "object": "tag",
        "object_id": "nofilter",
        "changed_aspect": "media",
        "time": 1297286541
    },
    ...
]

Thanks for any help.

Update 1

I've used PHP to print the HTTP headers. There's content because it show's it's length. Still unable to get at it though. This rules out it being an Instagram issue, I think


Solution

  • Woop found the problem and solved it. It's not easy to debug because all of this happens when Instagram hit your page so you don't really see the output.

    What I needed to do was create a foreach loop to run through the decoded JSON. After a lot of debugging and head scratching the JSON isn't empty, it just starts with a JSON array.

    Anyway here's the code now that works:

    // Catches realtime updates from Instagram
        if ($_SERVER['REQUEST_METHOD']==='POST') {
             // Retrieves the POST data from Instagram
            $update = file_get_contents('php://input');
            $data = json_decode($update);
    
            foreach($data as $k => $v) // can be multiple updates per call
            {
                $sub_id = $v->subscription_id; //Contains the JSON values
                $user = $v->object_id;
            }
         }
    

    If you want to see the outputs from $sub_id for example I suggest logging them or email them to yourself for example.