2011-09-29 29 views
0

首先我想道歉,如果這是有史以來最基本的問題!我不擅長PHP,但我正在學習。刷新後提取推文時出錯

我找不到解決方案,甚至不明白爲什麼它總是出錯。我確實想知道爲什麼發生這種情況

我試圖從Twitter帳戶中獲取最新的兩條推文。我不想使用我不瞭解的大量(現有的,我知道的)類或代碼。所以,我想下面的自己:

$timeline = "http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries"; 
    $data = file_get_contents($timeline); 
    $tweets = new SimpleXMLElement($data); 

    $i = 0; 
    foreach($tweets as $tweet){ 
     echo($tweet->text." - ".$tweet->created_at); 
     if (++$i == 2) break; 
    }

當我第一次跑這個代碼,我得到了我的鳴叫文本,但是當我刷新頁面我有時收到以下錯誤:

Warning: file_get_contents(http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /path/to/file on line 88

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /public/sites/www.singledays.nl/tmp/index.php:89 Stack trace: #0 /public/sites/www.singledays.nl/tmp/index.php(89): SimpleXMLElement->__construct('') #1 {main} thrown in /path/to/file on line 89

線88 & 89是這些:

$data = file_get_contents($timeline); 
$tweets = new SimpleXMLElement($data);

很奇怪。有時它有效,有時不會。

有沒有人知道這個問題和/或解決方案?爲什麼這個錯誤似乎是隨機發生的(Allthough它現在已經錯誤了一段時間了)?

謝謝!

+0

這需要進行基本的調試。呼叫失敗時'$ data'包含什麼?這不是有效的XML--它可能是來自Twitter的錯誤消息,因爲服務無法訪問,或者你在Twitter的結尾達到了一定的速率限制。 –

+0

PHP說它不能解析XML。捕捉異常並轉儲xml,以便您可以用肉眼來查看它。 –

+0

我的猜測是它與使用twitter api的限制有關。檢查https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following – Bob

回答

0
$timeline = "http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries"; 
$data = @file_get_contents($timeline); 

if($data){ 
    $fh = fopen("cache/".sha1($timeline),"w"); 
    fwrite($fh, $data); 
    fclose($fh); 
}else{ 
    $fh = @fopen("cache/".sha1($timeline),"r"); 
    $data = ""; 
    while(!feof($fh)){ $data = fread($fh, 1024); } 
    fclose($fh); 
} 

if(!$data) die("could not open url or find a cache of url locally"); 

$tweets = new SimpleXMLElement($data); 

$i = 0; 
foreach($tweets as $tweet){ 
    echo($tweet->text." - ".$tweet->created_at); 
    if (++$i == 2) break; 
} 

有,因爲每個人說調試你真的應該緩存結果中的文件,如果無法下載,然後使用緩存上面的代碼會爲你做它。

+0

現在我明白了,謝謝你幫助我! – Maurice