Facebook Graph API : Parsing the output - php

I am trying to get the names of my friends using FB Graph API with this call :
$friends = file_get_contents('https://graph.facebook.com/me/friendsaccess_token='.$session["access_token"]);
echo "Friends : $friends\n";
This gives me a list of the form :
{"data":[{"name":"ABC XYZ","id":"12212839"},{"name":"PQR GHI","id":"5004678"}]}
I want to be able to store only the NAMES in an array. How do I use $friends to get the names ? Something like $friends['name'] doesn't seem to work.
Please help.
Thank you.

$friends = json_decode($friends);
foreach($friends['data'] as $friend)
{
echo $friend['name'];
}
The return is a json object, you need to decode it. Although I strongly urge you to use an SDK such as http://github.com/facebook/php-sdk/
If this doesn't work try:
$friends = json_decode($friends);
foreach($friends->data as $friend)
{
echo $friend->name;
}

Here is what I did to get the posts information.. crude but it works. Note that the shares likes comments and reactions are one level deeper in the JSON object
$posts = json_decode($output); // from FB Graph v2.8 API call
foreach($posts->data as $post)
{
echo "MESSAGE: ", $post->message, "<br>";
echo "NAME: ", $post->name, "<br>";
echo "TYPE: ", $post->type, "<br>";
echo "ID: ", $post->id, "<br>";
echo "LINK: ", $post->link, "<br>";
echo "PERMALINK: ", $post->permalink_url, "<br>";
echo "CREATED: ", $post->created_time, "<br>";
if($post->shares->count == "") { $shares = "0"; } else { $shares = $post->shares->count; }
echo "SHARES: ", $shares, "<br>";
if($post->reactions->summary->total_count == "") { $reactions = "0"; } else { $reactions = $post->reactions->summary->total_count; }
echo "REACTIONS: ", $reactions, "<br>";
if($post->comments->summary->total_count == "") { $comments = "0"; } else { $comments = $post->comments->summary->total_count; }
echo "COMMENTS: ", $comments, "<br>";
if($post->likes->summary->total_count == "") { $likes = "0"; } else { $likes = $post->likes->summary->total_count; }
echo "LIKES: ", $likes, "<br>";
echo "<br><br>";
}

Related

How to remove a specific data from an API?

I'm working on a site which gives metrics of site, it uses API of gtmetrix. So i want to remove a specific data from the coming result but I just dont know how to do it. Some help would be appreciated!
<?php
require_once('service.inc.php');
$test = new Services_WTF_Test("email", "api_key");
$url_to_test = "https://google.me/";
echo "Testing $url_to_test\n";
$testid = $test->test(array(
'url' => $url_to_test
));
if ($testid) {
echo "Test started with $testid\n";
}
else {
die("Test failed: " . $test->error() . "\n");
}
echo "Waiting for test to finish\n";
$test->get_results();
if ($test->error()) {
die($test->error());
}
$testid = $test->get_test_id();
echo "Test completed succesfully with ID $testid\n'<br>";
$results = $test->results();
if ($results): ?>
<?php
foreach($results as $result => $data): ?>
<strong><?php $ukey = strtoupper($result);
echo $ukey; ?>:</strong>
<?php echo $data; ?><br><br>
<?php endforeach;
endif;
?>
The Output Is:
FIRST_CONTENTFUL_PAINT_TIME: 1495
PAGE_ELEMENTS: 44
REPORT_URL: https://gtmetrix.com/reports/google.me/BFylJNX3
REDIRECT_DURATION: 0
FIRST_PAINT_TIME: 1495
DOM_CONTENT_LOADED_DURATION:
DOM_CONTENT_LOADED_TIME: 1908
I want to remove the 3rd data from the api REPORT_URL:
You can skip REPORT_URL in foreach
$ukey = strtoupper( $result );
if( $ukey != 'REPORT_URL' ) {
echo '<strong>' . $ukey . '</strong>';
echo $data . '<br><br>';
}

php echo mysql array result in ajax

the below function is my controller code which is called by an ajax request:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$this->load->model('Featured_candidate', 'featured', TRUE);
$result = $this->featured->get_featured_candidates_by_skills($skills);
if ($result) {
$str = "";
foreach ($result as $row) {
$str .= "Name: " . $row->candidate_name . "<br/>";
$str .= "Exp: " . $row->experience . "<br/>";
$str .= "Skills: " . $row->skills . "<hr/>";
}
$html = $str;
echo json_encode(array('html' => $html, 'success' => TRUE));
} else {
$html = 'No Candidates Found!';
echo json_encode(array('html' => $html, 'success' => FALSE));
}
}
my view code:
<script>
$(function() {
$("#featured_candidates").on("change paste keyup", function() {
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>mypage/search_featured_candidates/",
data: {skills: $(this).val()},
dataType: "json",
success: function(data) {
if (data.success === true) {
$("#featured").html(data.html);
} else {
$("#featured").html(data.html);
}
}
});
});
});
</script>
<div class="panel-body">
<div>
<input type="text" style="width: 100%"
name="featured_candidates" id="featured_candidates"
placeholder="keyword / skills" title="Featured Candidates"
/>
<br/><hr/>
</div>
<div id="featured">
<?php
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . "<br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
?>
</div>
</div>
now i am trying to display the result array using ajax like i have displayed in my view code using foreach. so to display it using ajax i have concatenated the array in my controller method in $str but it is not working while when i updated my controller method to this:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$html = $skills ;
echo json_encode(array('html' => $html, 'success' => TRUE));
}
it is working fine..any help or suggesttion would be a great help...thanks in advance..
You have a mistake here
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . <br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
You forgot the "
. $row->candidate_name . "<br/>";
// ^ You forgot the "
The formulation of your question makes it difficult to know where your problem really is. But from a quick look you normally have to set proper headers in order to output json formatted data with PHP.
Try adding this before you do your echo, maybe this solves your problem:
header('Content-Type: application/json');

How to display a JSON API as an Array?

I'm just trying to display an API response as an Array, but something is wrong and I don't find it:
The API's answer:
{"status":"OK","minecrafts":[{"id":411,"ip":"2452453","name":"EdenCraft","port":23,"ram":512,"leaf_id":1522,"ftp_password":"1231235312","subscription_end":"2014-02-06T19:56:29.000Z"}]}
My PHP code:
<?php
$url = "http://api.edenservers.fr/minecraft?user_id=id&api_key=key";
$data = file_get_contents($url); // Opening the Query URL
$data = json_decode($data, true); // Decoding the obtained JSON data
if(count($data) > 0) {
foreach($data as $rank => $donnees) {
echo "<u>" . $rank ."</u> : ". $rank;
echo "<br />";
}
}
else {
echo "Rien n'a été troué.";
}
?>
And this is what's showed on my Dashboard:
status : status
minecrafts : minecrafts
Thanks for your help !
Try
foreach($data as $key=>$val){
if(is_array($val)){
foreach($val[0] as $key1=>$val1){
echo "<u>" . $key1 ."</u> : ". $val1;
}
}else{
echo "<u>" . $key ."</u> : ". $val;
}
}
Change:
echo "<u>" . $rank ."</u> : ". $rank
to:
echo "<u>" . $rank ."</u> : ". print_r( $donnees, TRUE )
Or the other way around if you want the values reversed. But the issue is with using $rank in both places.

PHP custom error issue

Currently, I have this code:
<?php
if (isset($_GET['s'])) {
$itemid = $_GET['s'];
$search = "$itemid";
$query = ucwords($search);
echo "<title>Results for $query</title>";
$string = file_get_contents('http://clubpenguincheatsnow.com/tools/newitemdatabase/items.php');
if ($itemid == "") {
echo "Please fill out the form.";
} else {
echo '<div id="content">';
$string = explode('<br>', $string);
foreach ($string as $row) {
preg_match('/^(.+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
if (preg_match("/$query/i", "$matches[1]")) {
echo "<a href='http://clubpenguincheatsnow.com/tools/newitemdatabase/info.php?id=$matches[2]'>";
echo $matches[1];
echo "</a><br>";
}
}
echo '</div>';
}
} else {
echo "Item does not exist!";
}
?>
If "$matches[1]" has nothing in it, I want my code it to echo "Item does not exist!" How do I do this though? Please help!
I've tried something like if ($matches[1]=="") { echo "Item does not exist!"; } before, but it didn't work. This is what I got:
http://img685.imageshack.us/img685/998/28990b2c12d0423292d3574.png
See works fine right? Look what happens if $matches[1] DOES exist:
http://img528.imageshack.us/img528/3690/71472c9de6ec49118ee8d48.png
It still comes up! How can I make my code so it only echos the error if there is nothing for $matches[1]? PLEASE HELP ME!
If you are wondering, this is my code when I added the if ($matches[1]=="") { echo "Item does not exist!"; } in:
<?php
if (isset($_GET['s'])) {
$itemid = $_GET['s'];
$search = "$itemid";
$query = ucwords($search);
echo "<title>Results for $query</title>";
$string = file_get_contents('http://clubpenguincheatsnow.com/tools/newitemdatabase/items.php');
if ($itemid == "") {
echo "Please fill out the form.";
} else {
echo '<div id="content">';
$string = explode('<br>', $string);
foreach ($string as $row) {
preg_match('/^(.+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
if (preg_match("/$query/i", "$matches[1]")) {
echo "<a href='http://clubpenguincheatsnow.com/tools/newitemdatabase/info.php?id=$matches[2]'>";
echo $matches[1];
echo "</a><br>";
}
}
echo '</div>';
if ($matches[1] == "") {
echo "Item does not exist!";
}
}
} else {
echo "Item does not exist!";
}
?>
Any help to my question would be VERY HIGHLY APPRECIATED!
Look at PHP's comparison operators
if (empty($matches[1])) { echo "Item does not exist!"; }
else {
echo "Item does not exist!";
}
This "else" is in regards to isset($_GET['s']). Is there a variable called s in your query string? If there isn't, then it's normal that you get the message.
Maybe you put that else block in the wrong place?

Foreach loop echo

The last foreach loop doesn't seem to echo the list I want, it doesn't print anything. How can I fix this? I know it's getting quite complicated but any help would be appreciated.
$allTroopsList = array();
$allMissionsList = array();
while ($mytroops = $alltroops->fetch_assoc())
{
$allTroopsList []= $mytroops;
}
while ($mymissions = $allmissions->fetch_assoc())
{
$allMissionsList []= $mymissions;
}
while($userintroop = $allUsersintroops->fetch_assoc())
{
if($userintroop['userid'] == $_SESSION['userid'])
{
echo "<ul class='troop'>";
echo "<li>" . $userintroop['troopid']. " </li>";
foreach($allTroopsList as $mytroops)
{
if($userintroop['troopid'] == $mytroops['troopid'])
{
echo "<li> Troop description: " . $mytroops['description']. " </li>";
foreach($allMissionsList as $mymissions)
{
if($mytroops['missionid'] == $mymissions['missionid'])
{
echo "<li> Missionname: " . $mymissions['missionname']. " </li>";
echo "<br/>";
echo "</ul>";
}
}
}
}
}
}
foreach($allUsers as $myotherusers)
{
if($userintroop['userid'] == $myotherusers['userid'])
{
echo "<li> other users: " . $myotherusers['username']. " </li>";
echo "<br/>";
}
}
This line:
while($userintroop = $allUsersintroops->fetch_assoc())
is fetching results from a database, right? That'd mean at some point you run out of rows to fetch, and $userintroop will become a boolean FALSE.
Then later on you try to do
if($userintroop['userid'] == $myotherusers['userid'])
which is wrong on two levels - $userintroop will NOT be an array at this point, so it could never have a ['userid'] parameter. And since it's the result of a failed fetch operation, never could have any value OTHER than a FALSE.
So that last loop does execute, but will never produce anything since the conditions for producing output are literally impossible to meet.

Categories