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("\n", "<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!
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