2011-09-29 38 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