PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 9, 2022

[FIXED] How To Extract Array Elements In Facebook PHP SDK

 January 09, 2022     facebook, facebook-graph-api, facebook-php-sdk, php     No comments   

Issue

$app_id = 'my_app_id';
$app_sec = 'my_app_secret';

session_start();

require_once 'fb_sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
FacebookSession::setDefaultApplication( $app_id , $app_sec );


$graph_url = "https://graph.facebook.com/search?&type=user&locale=en_US&q=randy+orton&limit=2&access_token=my_access_token";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$data = json_decode($result, true);

echo "<pre>";
var_dump($data);
echo "</pre>";

I get data after running it which is:

array(2) {
  ["data"]=>
  array(2) {
    [0]=>
    array(2) {
      ["name"]=>
      string(11) "Randy Orton"
      ["id"]=>
      string(15) "504099376411440"
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(11) "Randy Orton"
      ["id"]=>
      string(16) "1458654707784850"
    }
  }

But I'm unable to extract array elements. I tried different combinations in hopes of getting only names from returned data but that doesn't seem to be working.

var_dump($data);
var_dump($data['name']);
var_dump($data['data']['name']);
var_dump($result['name']);
var_dump($result['data']['name']);

How do I print names only from that data returned from Facebook???


Solution

$data['data'] is an array. So you have to call like below

var_dump($data['data'][0]['name']);

To print all the names you have to loop thorugh the data

for($i=0; $i<count($data['data']); $i++) {
    var_dump($data['data'][$i]['name']); 
}


Answered By - Saumini Navaratnam
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing