Archive for the ‘graph api’ Category

User’s Demographic Data from Facebook

Май 14th, 2010

facebookSometimes you may need to collect facebook user’s basic data for your website or application. Then you’ve to call graph api or legacy api or fql query to collect some specific data. This is a basic requirements for most of the fbconnect base website or facebook application.

For this reason, here I’m sharing the code, how could I collect those basic data and store them in database.

Before proceeding check the demo.

If you’re automatically logged in the site, then first logout and relogin and approve all the permissions. Now I’m showing the database table schema first

demographic

MySql code of this schema is:

CREATE  TABLE IF NOT EXISTS `demographic` (
  `uid` BIGINT UNSIGNED NOT NULL ,
  `first_name` VARCHAR(50) NULL ,
  `last_name` VARCHAR(50) NULL ,
  `email` VARCHAR(200) NULL ,
  `link` VARCHAR(255) NULL ,
  `affiliations` VARCHAR(255) NULL ,
  `birthday` VARCHAR(50) NULL ,
  `current_location` VARCHAR(200) NULL ,
  `education_history` VARCHAR(500) NULL ,
  `work` MEDIUMTEXT NULL ,
  `hometown_location` VARCHAR(400) NULL ,
  `interests` VARCHAR(200) NULL ,
  `locale` VARCHAR(50) NULL ,
  `movies` VARCHAR(500) NULL ,
  `music` VARCHAR(500) NULL ,
  `political` VARCHAR(200) NULL ,
  `relationship_status` VARCHAR(100) NULL ,
  `sex` VARCHAR(10) NULL ,
  `tv` VARCHAR(200) NULL ,
  `status` TINYINT NULL ,
  `created` DATETIME NULL ,
  `updated` DATETIME NULL ,
  PRIMARY KEY (`uid`) )
ENGINE = InnoDB

This code collects data from facebook

if ($fbme){
        //collect some data using legacy api
        $param  =   array(
            'method'     => 'users.getinfo',
            'uids'       => $fbme['id'],
            'fields'     => 'birthday_date, interests, locale, political, relationship_status, affiliations',
            'callback'   => ''
        );

        try{
            $info           =   $facebook->api($param);
        }
        catch(Exception $o){
            error_log("Legacy Api Calling Error!");
        }
        //using graph api
        //array data
        $workInfo       =   getWorkInfoAsString($fbme);
        $education      =   getEducationAsString($fbme);

        $moviesArr      =   $facebook->api("/me/movies");
        $musicArr       =   $facebook->api("/me/music");
        $televisionArr  =   $facebook->api("/me/television");

        //format some api data
        $movies         =   getArrayDataAsString($moviesArr['data']);
        $music          =   getArrayDataAsString($musicArr['data']);
        $television     =   getArrayDataAsString($televisionArr['data']);

        //data from legacy api
        $networks       =   '';
        if (!empty($info[0]['affiliations'])){
            $flag       =   true;
            foreach ($info[0]['affiliations'] as $item){
                if (!$flag)  $networks.= ' # ';
                $networks   .=  $item['name'];
                $flag   =   false;
            }
        }

        $now            =   date("Y-m-d G:i:s");
        $insData        =   array(
            'uid'                   =>  $fbme['id'],
            'first_name'            =>  $fbme['first_name'],
            'last_name'             =>  $fbme['last_name'],
            'email'                 =>  $fbme['email'],
            'link'                  =>  $fbme['link'],
            'affiliations'          =>  $networks,
            'birthday'              =>  $info[0]['birthday_date'],
            'current_location'      =>  $fbme['location']['name'],
            'education_history'     =>  $education,
            'work'                  =>  $workInfo,
            'hometown_location'     =>  $fbme['hometown']['name'],
            'interests'             =>  $info[0]['interests'],
            'locale'                =>  $info[0]['locale'],
            'movies'                =>  $movies,
            'music'                 =>  $music,
            'political'             =>  $info[0]['political'],
            'relationship_status'   =>  $info[0]['relationship_status'],
            'sex'                   =>  $fbme['gender'],
            'tv'                    =>  $television,
            'status'                =>  '0',
            'created'               =>  $now,
            'updated'               =>  $now,
        );

        //$this->db->insert('demographic', $insData);
    }

    function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){
        $info       =   "";
        $flag           =   false;
        foreach($fbme['work'] as $item){
            if ($flag)
                $info .= $partDelim;
            $flag   =   true;
            $info   .=  $item['employer']['name'] . $delim . $item['location']['name'] . $delim . $item['position']['name'] . $delim . $item['start_date'] . $delim . $item['end_date'];
        }
        return $info;
    }

    function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){
        $info       =   "";
        $flag           =   false;
        foreach($fbme['education'] as $item){
            if ($flag)
                $info .= $partDelim;
            $flag    =   true;
            $info   .=  $item['school']['name'] . $delim . $item['year']['name'];
        }
        return $info;
    }

    function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){
        $info       =   "";
        $flag           =   false;
        foreach($data as $item){
            if ($flag)
                $info .= $partDelim;
            $flag    =   true;
            $info   .=  $item['name'];
        }
        return $info;
    }

Look $insData contains all the values. So you just need to insert $insData in your database table. In this example I used mainly graph api, and for some small information I call legacy api. Regarding data storing format, if I found any data as array like education_history then I store that data like below format

[education_history] => International Islamic University Chittagong#2008 | Govt. Shah Sultan College, Bogra#2003

first # for part of a single data like (education institute and year), and finally | that separates array item. If your profile has well filled data then by visiting this demo you will see the data example.

So if you store education_history and next time you need to break them as array then you could write code like

$arrEdu      =  explode('|', $education_history); // break string to array items
$education = array();

$i = 0;
foreach($arrEdu as $item){
    $brk                             =   explode('#', $item);
    $education[$i]['institute'] =   $brk[0];
    $education[$i]['year']      =   $brk[1];
    ++$i;
}

echo '<pre>';
print_r($education);
echo '</pre>';

This will output

Array
(
    [0] => Array
        (
            [institute] => International Islamic University Chittagong
            [year] => 2008
        )

    [1] => Array
        (
            [institute] =>  Govt. Shah Sultan College, Bogra
            [year] => 2003
        )
)

If you read the code you’ll see its very easy to understand.

Full Source Code

<?php
    include_once "fbmain.php";
    $config['baseurl']  =   "http://thinkdiff.net/demo/newfbconnect1/demographicdata/index.php";

    //if user is logged in and session is valid.
    if ($fbme){
        //collect some data using legacy api
        $param  =   array(
            'method'     => 'users.getinfo',
            'uids'       => $fbme['id'],
            'fields'     => 'birthday_date, interests, locale, political, relationship_status, affiliations',
            'callback'   => ''
        );

        try{
            $info           =   $facebook->api($param);
        }
        catch(Exception $o){
            error_log("Legacy Api Calling Error!");
        }
        //using graph api
        //array data
        $workInfo       =   getWorkInfoAsString($fbme);
        $education      =   getEducationAsString($fbme);

        $moviesArr      =   $facebook->api("/me/movies");
        $musicArr       =   $facebook->api("/me/music");
        $televisionArr  =   $facebook->api("/me/television");

        //format some api data
        $movies         =   getArrayDataAsString($moviesArr['data']);
        $music          =   getArrayDataAsString($musicArr['data']);
        $television     =   getArrayDataAsString($televisionArr['data']);

        //data from legacy api
        $networks       =   '';
        if (!empty($info[0]['affiliations'])){
            $flag       =   true;
            foreach ($info[0]['affiliations'] as $item){
                if (!$flag)  $networks.= ' # ';
                $networks   .=  $item['name'];
                $flag   =   false;
            }
        }

        $now            =   date("Y-m-d G:i:s");
        $insData        =   array(
            'uid'                   =>  $fbme['id'],
            'first_name'            =>  $fbme['first_name'],
            'last_name'             =>  $fbme['last_name'],
            'email'                 =>  $fbme['email'],
            'link'                  =>  $fbme['link'],
            'affiliations'          =>  $networks,
            'birthday'              =>  $info[0]['birthday_date'],
            'current_location'      =>  $fbme['location']['name'],
            'education_history'     =>  $education,
            'work'                  =>  $workInfo,
            'hometown_location'     =>  $fbme['hometown']['name'],
            'interests'             =>  $info[0]['interests'],
            'locale'                =>  $info[0]['locale'],
            'movies'                =>  $movies,
            'music'                 =>  $music,
            'political'             =>  $info[0]['political'],
            'relationship_status'   =>  $info[0]['relationship_status'],
            'sex'                   =>  $fbme['gender'],
            'tv'                    =>  $television,
            'status'                =>  '0',
            'created'               =>  $now,
            'updated'               =>  $now,
        );

        //$this->db->insert('demographic', $insData);
    }

    function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){
        $info       =   "";
        $flag           =   false;
        foreach($fbme['work'] as $item){
            if ($flag)
                $info .= $partDelim;
            $flag   =   true;
            $info   .=  $item['employer']['name'] . $delim . $item['location']['name'] . $delim . $item['position']['name'] . $delim . $item['start_date'] . $delim . $item['end_date'];
        }
        return $info;
    }

    function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){
        $info       =   "";
        $flag           =   false;
        foreach($fbme['education'] as $item){
            if ($flag)
                $info .= $partDelim;
            $flag    =   true;
            $info   .=  $item['school']['name'] . $delim . $item['year']['name'];
        }
        return $info;
    }

    function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){
        $info       =   "";
        $flag           =   false;
        foreach($data as $item){
            if ($flag)
                $info .= $partDelim;
            $flag    =   true;
            $info   .=  $item['name'];
        }
        return $info;
    }
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Facebook User's Demographic Data Collection | Thinkdiff.net</title>
    </head>
<body>
    <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: '<?=$fbconfig['appid' ]?>', status: true, cookie: true, xfbml: true});

                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());

            function login(){
                document.location.href = "<?=$config['baseurl']?>";
            }
            function logout(){
                document.location.href = "<?=$config['baseurl']?>";
            }
</script>
    <h3>Facebook User's Demographic Data Collection | Thinkdiff.net</h3>
    <?php if (!$fbme) { ?>
        You've to login using FB Login Button to see your demographic data
    <?php } ?>
    <p>
        <fb:login-button autologoutlink="true" perms="email,publish_stream,offline_access,user_birthday,user_location,user_work_history,user_religion_politics,user_relationships"></fb:login-button>
    </p>

    <!-- all time check if user session is valid or not -->
    <?php
        if ($fbme){
            echo '<pre>';
            print_r($insData);
            echo '</pre>';
        }
     ?>
    </body>
</html>

Hope this code will help you to quickly integrate in your project. This data collection code will work in both canvas application and fbconnect base application. You can modify the code easily to get customize data. But fyi this code doesn’t collect all the information of facebook user rather some basic and essential information

And don’t forget extended permission list. I provided this list of permissions as I needed to collect above data.

<fb:login-button autologoutlink="true" perms="email,publish_stream,offline_access,user_birthday,user_location,user_work_history,user_religion_politics,user_relationships"></fb:login-button>



PlanetMySQL Voting: Vote UP / Vote DOWN