2012-06-22 56 views
1

我正在运行一个php网站,并希望从我公司的twitter feed中获取最新的tweet。以下是我拥有的代码,但目前无法使用。我做错了什么?我是否需要更改Twitter中的任何设置才能使此方法起作用?使用Json获取Twitter消息

$responseJson = file_get_contents('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=take_me_fishing&include_rts=1&count=1'); 

if ($responseJson) 
{ 
    $response = json_decode($responseJson);     
    $status = $response->text; 
} 
+1

什么是“不工作”要访问的第一个元素的“文本”属性,如下所示修改代码意思?怎么了?代码看起来很好。也许'file_get_contents'失败,因为'php.ini'中的指令阻止了通过网络读取数据? –

+0

您不必在Twitter设置中更改任何内容。尝试在浏览器中打开网址。有用。你的php代码一定有问题。 – simbabque

+0

感谢大家的快速响应!事实证明,这很简单,因为缺少数组括号。 –

回答

0

$response的值是一个对象数组。由于您仅检索最后一个,因此您需要访问此数组中的第一个项目。

if ($responseJson) { 
    $response = json_decode($responseJson); 
    $status = $response[0]->text; 
} 

print $status; // The tweet. 

注意,当你print_r($response)你会看到如下结构:

Array 
(
    [0] => stdClass Object 
    (
     [created_at] => Fri Jun 22 15:00:34 +0000 2012 
     [id] => 216183907643699200 
     [id_str] => 216183907643699200 
     [text] => Help us determine the Top 8 State Parks for boating and fishing: 
       http://t.co/SQEzWpru #takemefishing 
     ... rest of the tweet object ...