Facebook图形到阵列

Moe*_*Moe 0 php arrays api facebook

我一直在寻找将Facebook Graph API数据转换为数组的方法,以便我可以快速访问"赞"数据,以便在我的网站上使用.

我目前正在使用此代码在特定链接上提取"Shares"(aka,Like's).

    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;
Run Code Online (Sandbox Code Playgroud)

这是Graph API返回的内容:(在页面"https://graph.facebook.com/[LINK]"时)

{
   "id": "MY URL",
   "shares": 302
}
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以轻松地将此处的信息转换为数组吗?所以最终产品将变成如下:

$fbArray["id"] // will Return: MY URL
Run Code Online (Sandbox Code Playgroud)

$fbArray["shares"] // will Return: 302
Run Code Online (Sandbox Code Playgroud)

我的方法很有效,但它很邋and,而且根本不是非常动态的编码!

任何帮助将不胜感激.

JAL*_*JAL 8

Facebook正在以JSON格式返回数据!您似乎正在用正则表达式解析它.我相信大多数人都强烈建议不这样做.

相反,使用PHP的json_decode函数.将它true作为第二个参数传递给你一个数组,而不是一个对象.

$fb = file_get_contents("https://graph.facebook.com/$url", "rb");
$fb_array=json_decode($fb,true);
Run Code Online (Sandbox Code Playgroud)