Reputation: 667
I am trying to get the count of the no of mutual friends I have with all my friends.
foreach($friends_list as $friend)
{
$id = $friend['id'];
$name = $friend['name'];
$arr = $facebook->api('/me/mutualfriends/'.$id);
$arr = $arr['data'];
$count = count($arr);
$totalcount = $totalcount + $count;
$i++;
echo $id. " " .$name . " " . $count . "</br>";
}
But I am getting timed out like after getting data of around 20 frnds. How should I go about optimizing it?
Upvotes: 0
Views: 524
Reputation: 5920
Update the 'max_execution_time' settings in your php.ini file. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.
http://php.net/manual/en/function.set-time-limit.php
Upvotes: 0
Reputation: 25918
You getting timeout in your script because of configuration settings for max_execution_time
in php.ini
and this can be easily avoided if you'll use something like this before running that long op:
set_time_limit(0);
// execute long running code...
Doing many requests to external services in a loop is bad and there is couple of way to improve your code to be much faster.
Option 1: You may use Batch Requests for Graph API to run several requests (up to 50) at once.
Option 2: You may get mutualfriends
connection in other direction (getting results for several friends at once).
https://graph.facebook.com/mutualfriends/YOUR_ID?ids=friend_1,friend_2,friend_n
This is generally the same as:
https://graph.facebook.com/friend_1/mutualfriends/YOUR_ID
https://graph.facebook.com/friend_2/mutualfriends/YOUR_ID
https://graph.facebook.com/friend_n/mutualfriends/YOUR_ID
Upvotes: 1
Reputation: 8529
I'd suggest putting a sleep
in that loop as to not overload the server.
e.g.
foreach( $friends_list as $friend )
{
$id = $friend['id'];
$name = $friend['name'];
$arr = $facebook->api('/me/mutualfriends/'.$id);
$arr = $arr['data'];
$count = count($arr);
$totalcount = $totalcount + $count;
$i++;
echo $id. " " .$name . " " . $count . "";
usleep( 100000 );
}
To wait 100 milliseconds after each request.
Upvotes: 0