Search code examples
phpjsonfacebook-graph-apitexttrimming

Trim locale result from Facebook Graph API


I am using the Facebook Graph API to get the users locale information (updated code):

[more code]
<div id="scoreboard-overview">
    <ul>';
    $num_rows = mysql_num_rows($resulttt);
    $i = 0;
        while($row = mysql_fetch_array($resulttt)) {
            $i = $i + 1;
            $fb_data = json_decode(file_get_contents('http://graph.facebook.com/'. $row['fbID']));
            $fb_locale_str = $fb_data->locale;
            $fb_name_str = $fb_data->first_name;
            $fb_country_str = strtolower(substr($fb_locale_str, -2));
            $flag_uri = '/flags/unknown.gif'; //display a general flag if unknown.
            if (!empty($fb_country_str) && in_array($fb_country_str, $valid_flags) )
                $flag_uri = '/flags/' . $fb_country_str . '.gif';

echo '<li>
        <div class="container">
            <div class="black">
                <img src="https://graph.facebook.com/'. $row['fbID'] .'/picture" alt="" />
            </div>
            <div class="grey">
                '.$i.' '.$fb_name_str.'';
            printf ('<div class="test"><img src="%s" /></div>', $flag_uri); 
    echo '      </div>
            <div class="holder">
                <div class="blue">
                    <p>0<br />'. $row['Time'] .'</p>
                </div>
                <div class="red">
                    <img src="http://ep2.nl/images/star.gif" alt="" />
                </div>
                <div class="yellow">
                    <p>'. $row['Score'] .'</p>
                </div>
            </div> 
        </div>
    </li>';
        }
echo '</ul>
</div>
    [more code]

$row['fbID'] is the users and/or friends Facebook ID (used in a array)

Well this gives a result like: en_US where en is the users language and US is the users country. The country is where I am after.

I have a couple of flag images that look like this: us.png. These flags are named using the ISO3166-1 alpha-2 country codes where appropriate. So I want to trim this en_US to us and put .png behind it so I can show the flag image. But how to do this?

Also a general flag if the locale returns nothing like unknown.png would be nice.

Many thanks,

Maurice


Solution

  • Not too hard to do.

    Try this:

    $valid_flags = array ('us', 'ca', 'mx', '...') //You'll need to populate this one
    
    $fb_data = json_decode(file_get_contents('http://graph.facebook.com/'. $row['fbID']);
    $fb_locale_str = $fb_data->location;
    $fb_country_str = strtolower(substr($fb_locale_str, -2));
    $flag_uri = '/flags/unknown.png'; //display a general flag if unknown.
    if (!empty($fb_country_str) && in_array($fb_country_str, $valid_flags) )
        $flag_uri = '/flags/' . $fb_country_str . '.png';
    printf ('<div class="grey"><img src="%s" /></div>', $flag_uri);
    

    As a note, you shouldn't be calling file_get_contents inside of an echo statement.