Pages

Wednesday, May 18, 2011

Get facebook friends list in an array

Here is the solution for getting facebook friends list in an array usinbg PHP

First of all you need to download latest facebook php sdk from https://github.com/facebook/php-sdk/downloads
 Then include facebook.php from the sdk directory to your php page.

 After that use below code to generate friends list in a array
 --------------------------------------------------------------------------------------------------------
$facebook = new Facebook(array(
  'appId'  => 'APP-ID',
  'secret' => 'APP-SECRET-KEY',
  'cookie' => true,
));

$friends = $facebook->api('/'. FACEBOOK-USER-ID .'/friends');
                $friendsList = array();
                foreach ($friends as $key=>$value)
                {
                   foreach ($value as $fkey=>$fvalue) {

                       $friendsList[] = $fvalue[id];
                   }

                }


print_r($friendsList);
 --------------------------------------------------------------------------------------------------------

2 comments:

  1. I think this might be quite useful, if you want to know the whole process of getting it from FQL -> PHP -> Javascript
    Hope it works. And I hope i avoided spelling mistakes.
    '12345678910',
    'secret' => '40b030303040vsomenumber',
    ));
    $userid = $facebook->getUser();
    $friends = $facebook->api('/'. $userid .'/friends');
    $friendsList = array();
    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("circles");
    $parnode = $dom->appendChild($node);
    //Your SQL Query,
    $query = sprintf("SELECT userid FROM fbUser");
    $result = mysql_query($query);
    if (!$result) {
    die('Invalid query: ' . mysql_error());
    }
    header("Content-type: text/xml");

    // Iterate through the rows, adding XML nodes for each friend
    }
    foreach ($friends as $key=>$value)
    {
    foreach ($value as $fkey=>$fvalue) {
    //if you only want to store in an array take code from php-experts
    //$friendsList[] = $fvalue[id];
    $node3 = $dom->createElement("friends");
    $newnode = $parnode->appendChild($node3);
    $newnode->setAttribute("id", $fvalue[id]);

    }
    }
    echo $dom->saveXML();
    ?>

    echo $dom->saveXML();
    ?>


    --------->read friends list out in Javascript and store in array:>

    downloadUrl("yourPHP.php?", function(data) {
    var xmlfriends = data.documentElement.getElementsByTagName("friends");
    var ff = xmlfriends.length;
    var friendsList = [];
    for(var abc = 0; abc < ff; abc++){
    var friendsId = parseInt(xmlfriends[abc].getAttribute("id"));
    friendsList.push(friendsId);
    }
    });

    ReplyDelete
  2. It is really a great work and the way you sharing the knowledge is excellent.
    php development melbourne | hire angularjs developer

    ReplyDelete