get page contents and json_decode loading issue
I have开发者_如何学运维 the following code that makes a call to facebook's open graph and returns an object with shares and an id. The only issue is that I am making this call 30 times and it is taking over 9 seconds to load. Is there an easier way to get straight to the point and just get the shares so this loads faster?
//facebook
$fdata = file_get_contents('http://graph.facebook.com/http://theoatmeal.com/comics/127_hours');
$fdata = json_decode($fdata);
if($fdata->shares) {
$share_count['facebook'] = $fdata->shares;
}
This is what i use for decode from graph.facebook.com
<?php
$info = "http://theoatmeal.com/comics/127_hours";
$url = "http://graph.facebook.com/". $info . "";
$geturl = file_get_contents($url);
$info = json_decode($geturl);
{
$id = $info->id;
$shares = mysql_real_escape_string($info->shares);
?>
<?php echo $id;?><br>
<?php echo $shares;
}
?>
A good an easy way to proceed is to use the Facebook PHP SDK (see on github). First you have to make sure the user is logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he is logged in, you are able to make API calls :
$result = $facebook->api(...);
If he is not, you have to log him in :
<?php if ($user): ?>
<a href="<?php echo $facebook->getLogoutUrl() ?>">Logout of Facebook</a>
<?php else: ?>
<a href="<?php echo $facebook->getLogoutUrl() ?>">Login with Facebook</a>
<?php endif ?>
Hope that helps !
I did not understand well your question the first time so I try to give another shot.
You can use FQL to make your query :
$fql = 'SELECT total_count FROM link_stat WHERE url="http://google.com"';
$json = file_get_contents('https://api.facebook.com/method/fql.query?format=json&query=' . urlencode($fql));
$data = json_decode($json);
echo $data[0]->total_count;
Here, total_count
gives you the number of shares for the link.
If you have several URL to query, you can make all of that in only one query by using OR
:
SELECT url, total_count FROM link_stat WHERE url="..." OR url="..."
Here is an example is you want to get the number of shares for thoses 4 URLs :
$urls = array(
"http://google.com",
"http://twitter.com",
"http://stackoverflow.com",
"http://linkedin.com"
);
function wrap($url) {
return 'url="' . $url . '"';
}
$fql = 'SELECT url, total_count FROM link_stat WHERE ';
$fql .= implode(" OR ", array_map("wrap", $urls));
$json = file_get_contents('https://api.facebook.com/method/fql.query?format=json&query=' . urlencode($fql));
$data = json_decode($json);
And $data
is an array of 4 objects with the share number for each URL :
array(4) {
[0]=> object(stdClass)#2 (2) {
["url"]=> string(17) "http://google.com"
["total_count"]=> int(1318598)
}
[1] => ...
[2] => ...
[3] => ...
}
Hope that helps !
精彩评论