phpfacebookperformancefacebook-graph-apifql.multiquery

Increasing the performance and usability of Facebook's FQL


I try to get some insights from the pages I am administrator on Facebook.
What my code does, it gets the IDs of the pages I want to work with through mySQL. I did not include that part though.

After this, I get the page_id, name and fan_count of each of those facebook IDs and are saved in fancounts[].

I have two problems with it.

  1. It has a very slow performance
  2. I can't find a way to echo the data like this:

My questions are, how can the code be modified to increase performance and show the data as above? I read about fql.multiquery. Can it be used here?

Please provide me with code examples. Thank you


Solution

  • If you have n pages, your script makes n+1 queries. This is the main drawback of your script. This is the reason for low performance.

    You can use batch request to combine the queries. You can use the below script to achieve what you want. I have combined those n+1 queries to just one batch query. So it will be mush faster than your script.

    I've also corrected the echo part. Now the script will display the output as you stated in your question.

    // Get the IDs
    $pages = array(); 
    $pagesIds = implode(',', $pages);
    
    // fancounts[] holds the page_id, name and fan_count of the Ids I work with
    $fancounts = array();
    $q = "SELECT page_id, name, fan_count FROM page WHERE page_id IN ({$pagesIds})";
    $queries[] = array('method'=>'GET', 'relative_url' => 'method/fql.query?query=' . urlencode($q) );
    
    $messages = array();
    foreach( $pages as $id) 
    {
       $q = "SELECT message FROM stream WHERE source_id = '$id' LIMIT 2";
       $queries[] = array('method'=>'GET', 'relative_url' => 'method/fql.query?query=' . urlencode($q) );
    }
    
    // The batch query
    $batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
    $pagesFanCounts = json_decode($batchResponse[0]['body'], TRUE);
    
    foreach ($pagesFanCounts as $page)
    {       
       $fancounts[] = number_format($page['page_id'],0,'','')."-".$page['name']."-".$page['fan_count'];
    }
    
    for($i=0; $i < count($fancounts); $i++) 
    {
       echo '</br>',$fancounts[$i],'<br>';
       $temp = json_decode($batchResponse[$i+1]['body'], TRUE);
       foreach ($temp as $msg)
       {
          echo ($msg['message']);
          echo "</br>";
       }
    }