2012-06-22 55 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 ...