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/%5BLINK%5D”)
{
"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.
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
trueas the second param will give you an array, rather than an object.