douyue5856 2016-02-19 17:27
浏览 78
已采纳

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('https://graph.facebook.com/'.$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('https://graph.facebook.com/'.$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>
            </div>
            <?php
        }
    }
}

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?

Thanks!

  • 写回答

1条回答 默认 最新

  • 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: https://developers.facebook.com/docs/graph-api/using-graph-api/#fieldexpansion

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!