views:

36

answers:

1

Hey Forum,

I've been looking around for a way to convert Facebook Graph API Data into Array's so I can quickly access 'Like' Data for use on my website.

I'm currently using this code to extract 'Shares' (aka, Like's) on a particular link.

    fb = file_get_contents("https://graph.facebook.com/$url", "rb");
    $fb = str_replace('}','',$fb);
    $fb = str_replace('{','',$fb);

    $e = explode(',',$fb);

   for($i = 0; $i < count($e); $i++)
   {
        if(preg_match("/\"shares\"\:/i",$e[$i]))
        {
            $c = substr($e[$i],9);
        }
    }

echo $c;

This is what the Graph API returns: ( When on the page "https://graph.facebook.com/[LINK]")

{
   "id": "MY URL",
   "shares": 302
}

Is there anyway I can easily transform the information here into an Array? So the final product will become something like:

$fbArray["id"] // will Return: MY URL

and

$fbArray["shares"] // will Return: 302

My method Works, but it's sloppy and really not very dynamic coding at all!

Any help will be appreciated.

+3  A: 

Facebook is returning data in the JSON format! You appear to be parsing it with a regex. I'm sure most everyone here strongly recommends not doing that.

Instead, use PHP's json_decode function. Passing it true as the second param will give you an array, rather than an object.

$fb = file_get_contents("https://graph.facebook.com/$url", "rb");
$fb_array=json_decode($fb,true);
Alex JL
(by the way, I parsed XML like this when I was first starting out - even worse, using `exec` to run grep, sed and awk. When you see a data structure, remember there's almost always a non-hacky, easy method to work with it in PHP/Python/etc!)
Alex JL
You are my new god. Thanks Alex.
Moe
Ha, I'm glad I was able to help.
Alex JL