PHP script to retrieve Facebook Posts using the Graph API

Looking to retrieve posts from a Facebook page? You can check it out here. However, there seems to be a slight delay in loading the page (approximately 4-5 seconds).

I suspect that using 2 "foreach" loops to fetch the data might be causing this issue.


Below is the snippet of 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
        }
    }
}

I have omitted the "page_id" and "access_token" variables for security reasons.

Any suggestions on how I could improve the performance of the page load?

Thank you!

Answer №1

Absolutely, it will be sluggish if you trigger multiple API requests within a loop.
(The main cause of the slowdown is the HTTP request that your application sends to interact with Facebook's servers - and if you send individual API requests in a loop, this results in one HTTP request for each of them.)

Instead, utilize field expansion to retrieve all the data in a single request: https://developers.facebook.com/docs/graph-api/using-graph-api/#fieldexpansion

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The cache data is not displaying the expected result upon filtering in Laravel 5.1

What is this all about? Exploring different methods to filter the cache data. Here's a snippet of code showcasing two approaches. Approach : 1 $Categories = \Cache::rememberForever('Categories', function() { return \App&bsol ...

Creating JSON Query Output in Codeigniter

My database table is called usermeta and it has the following structure : ----------------------------------------------------------- | ummeta_id | user_id | meta_key | meta_value | ----------------------------------------------------------- | ...

Using PHP to implement conditional statements for multiple days of the week

Could this be done? $d=date("D"); ... else if ($d=='(Thu|Fri|Sat)') { I have managed to make it work for one day of the week. if ($d=='Wed') { Thank you ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...

Removing the final character in a loop iteration

Is there a way to remove the final pipe character from the list of generated numbers? $days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6); foreach ($days as $day) { echo strtoupper($day->format('d')+543); ech ...

Performing a single AJAX call from a JavaScript loop is more efficient than iterating through multiple AJAX calls

I am working with a 2D array in JavaScript. Currently, I have a for loop where I make an AJAX call to update the database. I understand that this approach is not efficient, and I am seeking a way to update the database with just one AJAX call within the ...

Does the user need to download the scripts from Google API multiple times during the insertion process?

Concerned about the potential need for multiple downloads of a script from an unknown location on the user's computer, I would like to explore options to mitigate this issue. Specifically, I am considering creating a condition to check the download st ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

Discovering and Monitoring Viruses on a WordPress Website

My dedicated server is set up with WHM/cPanel CentOS Apache. One of the accounts on cPanel is hosting a WordPress site that has been infected with a virus. This virus is being used to send emails and inject affiliate links without authorization. Despite ...

Checking against the database with a loop versus performing a quick lookup

Recently, I've been facing a challenging issue that has been giving me quite a headache. I could really use your expertise on this. The situation is as follows: I have two collections - Customers (A) and their payment history (B). My goal is to retri ...

Restricting requests to only .json files is possible on an Apache server by using the

I am looking to implement a specific functionality on my live underdeveloped website that is accessible on the internet with remote access. This website produces both php/html content for human visitors and .json output for the API. My current requirement ...

php code to show data in a single column of a table

I am working with a database record that includes an id and name, and I need to display it in a table where records are distributed in the pattern 1-2-1-2-4 across columns. Below is my current code that is generating the incorrect output: <table borde ...

Looking to display the "loading....." message on a PHP page?

I am working on a PHP webpage where I need to implement the following features: 1. Upon clicking "Say Thanks", it should change to "Done!". 2. Simultaneously, I would like to trigger an action in the indexController. 3. While this action is happening, I wa ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...

Navigating through the outputs from a MySQL query

There is a specific functionality I am trying to achieve, although I may not have the exact terms to describe it. Let me explain what I need in detail. Initially, there is a variable named $id, which essentially represents $_GET['id']. For insta ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

What is the best way to send a CURL request to an IP Address using PHP?

I've been attempting to send a CURL request to an IP address, but for some reason it keeps failing without any clear explanation. Here's the code I'm working with: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"127.0.0.1/script.php"); cu ...