Se avete una pagina su Facebook vorrete probabilmente conoscere alcuni dei dati statistici della vostra pagina. Per esempio potreste voler sapere quanti fan avete. Ecco come fare con PHP.
I dati JSON
Per prima cosa occorre conoscere la struttura JSON restituita da Facebook. Se puntate il vostro browser all'indirizzo https://graph.facebook.com/nomepagina otterrete qualcosa come la seguente struttura:
{
   "id": "...",
   "name": "Gabriele Romanato",
   "picture": "...",
   "link": "http://www.facebook.com/gabrieleromanatopage",
   "likes": 27,
   "category": "Public figure",
   "website": "https://gabrieleromanato.com/",
   "username": "gabrieleromanatopage",
   "about": "Gabriele Romanato. Italian web developer. ",
   "bio": "...",
   "birthday": "...",
   "personal_interests": "...",
   "can_post": true,
   "talking_about_count": 1
}
Ora dobbiamo solo estrarre i dati che ci interessano.
Il codice PHP
Creiamo la seguente funzione:
function fbFanCount($facebookName = 'gabrieleromanatopage')
{
    
    $json = file_get_contents('https://graph.facebook.com/' . $facebookName);
    
    if($json) {
    
    	$data = json_decode($data);
    	
    	return $data->likes;
    
    } else {
    
    	return 'Errore';
    
    }
}
Esempio d'uso:
[php htmlscript="true"] <div class="fb-fan-count"> <?php echo fbFanCount(); ?> fan </div>