2011-05-31 60 views
-1

我有以下代码,它会调用Facebook的打开图并返回一个包含共享和ID的对象。唯一的问题是我正在进行这个调用30次,并且要花9秒多才能加载。有没有一种更简单的方法可以直接找到并获取股份,从而加快速度?获取页面内容和json_decode加载问题

//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; 
} 

回答

0

一个好一个简单的方法来进行是使用Facebook的PHP SDK(see on github)。首先,你必须确保用户登录:

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; 
    } 
} 

如果他登录,您就可以进行API调用:

$result = $facebook->api(...); 

如果他不是,你必须登录他在:

<?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 ?> 

希望帮助!

+0

我很欣赏这一点,但我觉得这是多一点的话,我会想要做的这一个。我想保持简单,不必加载任何额外的代码,这可能会导致更多的加载时间。 – 2011-05-31 23:23:05

+0

你想做什么?你没有提供足够的信息。你想要做什么API调用? – Quentin 2011-05-31 23:26:37

+0

请参阅编辑。我试图获得Facebook的份额。请转至file_get_contents函数中的URL – 2011-05-31 23:31:01

0

我第一次不明白你的问题,所以我尝试再次拍摄。

您可以使用FQL,使您的查询:

$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; 

在这里,total_count给你的股票该链接的数量。

如果你有几个网址查询,您可以通过使用OR使所有的,在只有一个查询:

SELECT url, total_count FROM link_stat WHERE url="..." OR url="..." 

下面是一个例子是你想要得到的股份数量为放入系统4个网址:

$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); 

而且$data是4个对象的与每个URL的份数的数组:

array(4) { 
    [0]=> object(stdClass)#2 (2) { 
    ["url"]=> string(17) "http://google.com" 
    ["total_count"]=> int(1318598) 
    } 
    [1] => ... 
    [2] => ... 
    [3] => ... 
} 

希望有所帮助!

1

这是我使用的解码从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; 
} 
?>