Extracting Infos from an external JSON by php

Asked

Viewed 109 times

0

<?php
  $json = "https://graph.facebook.com/264449740579494?access_token=EAACFJ0t0JZAMBAHQYJ1f1DuWZBVmS9FyUKPGIzAqVO9z8EqdFLw0SqZB7E7mDzKiLfHdmHaivO5lwOuU7MZAhmz2810rwRy85IGMwfZAPtSNYEypfgfW9uIIA5tXJS5qSZCjk5YnFg9iXUGPKc0lNXZAgXqirfCA8gJ1hQa2VQ9hhAGlp0ooFYmr2ykws7jebktYIYwtsYNKAZDZD&fields=fan_count";
  $json = var_dump(json_decode($json, true));
  echo $json['fan_count'];
?>

How do I extract the "fan_count" number from this json? It only returns NULL

  • First, you need to make an HTTP request to get the JSON back. For now you are trying to parse a URL as if it were JSON. Second, we’ll need to know the structure of the returned JSON to tell us how to access the desired value.

  • In that case the simple can be expensive.

2 answers

0

Using Curl, being a library for communication of several servors and also several protocols, the contents of this address are downloaded in the format json:

{
   "fan_count": 185,       
   "id": "264449740579494"
}

and with the function json_decode decodes a JSON string for a array associative or an object according to configuration in its second parameter, example:

<?php

    $url = 'https://graph.facebook.com/264449740579494?access_token=EAACFJ0t0JZAMBAHQYJ1f1DuWZBVmS9FyUKPGIzAqVO9z8EqdFLw0SqZB7E7mDzKiLfHdmHaivO5lwOuU7MZAhmz2810rwRy85IGMwfZAPtSNYEypfgfW9uIIA5tXJS5qSZCjk5YnFg9iXUGPKc0lNXZAgXqirfCA8gJ1hQa2VQ9hhAGlp0ooFYmr2ykws7jebktYIYwtsYNKAZDZD&fields=fan_count';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $json = curl_exec($ch);    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpCode == 200)
    {
        $array = json_decode($json, true);
        echo $array['fan_count'];
    }
    curl_close($ch);
  • 1

    beauty, using that Curl worked.

0


A simple solution is to use file_get_contents

<?php
$json = "https://graph.facebook.com/264449740579494?access_token=EAACFJ0t0JZAMBAHQYJ1f1DuWZBVmS9FyUKPGIzAqVO9z8EqdFLw0SqZB7E7mDzKiLfHdmHaivO5lwOuU7MZAhmz2810rwRy85IGMwfZAPtSNYEypfgfW9uIIA5tXJS5qSZCjk5YnFg9iXUGPKc0lNXZAgXqirfCA8gJ1hQa2VQ9hhAGlp0ooFYmr2ykws7jebktYIYwtsYNKAZDZD&fields=fan_count";
$json = json_decode(file_get_contents($json), true);
echo $json['fan_count'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.