2016-02-19 17:27 阅读 64

Facebook Graph API - 用PHP获取帖子

Im trying to get posts from a Facebook page. I did that in here The problem is that the page is a little bit slow (4 or 5 seconds to load)

I am using 2 "foreach" to get the data and maybe thats the problem.

Here is my code:

$json_object = @file_get_contents(''.$page_id.'/posts?limit=4&access_token=' . $access_token);

$fbdata = json_decode($json_object);

foreach ($fbdata->data as $post)
$postid = $post->id;

    $json_object2 = @file_get_contents(''.$postid.'/attachments?access_token=' . $access_token);

    $fbdata2 = json_decode($json_object2);

    foreach ($fbdata2->data as $post2)
        $title = $post2->title;
        $type = $post2->type;
        $url = $post2->url;
        $desc = $post2->description;
        $desc = str_replace("
", "<br>", $desc);
        if (strlen($desc) > 200){
           $desc = substr($desc, 0, 200) . '...<br>...<br><a href="'.$url.'" target="_blank">Ver mais</a>';

        $imgsrc = $post2->media->image->src;
        if ($type=="note") {
            <div class="wrapper">
                <a href="<?php echo $url;?>" target="_blank"><div class="img" style="background-image: url('<?php echo $imgsrc; ?>');"></div></a>
                <a href="<?php echo $url;?>" target="_blank"><h1><?php echo $title; ?></h1></a>
                <p><?php echo $desc; ?></p>

Im not showing you the "page_id" and "access_token" variables but they are correct.

What can I do to get a better performance in the page load?


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dtkjthe4025 dtkjthe4025 2016-02-24 08:41

    Yes, of course it is slow if you fire a number of API requests inside a loop.
    (The most slowing part is the HTTP request your app makes to talk to Facebook’s servers – and if you make single API requests in a loop, that means one HTTP request for each one of them.)

    Use field expansion instead, to request all that data in one go:

    点赞 评论 复制链接分享