刷新后获取推文时出错


error with fetching tweets after refresh

首先,如果这是最基本的问题,我想道歉!我不太擅长php,但我正在学习。

我找不到解决方案,甚至不明白为什么它总是出错。我确实想知道为什么会发生这种情况

我正试图从一个推特账户中获取两条最新的推文。我不想使用大量(现有的,我知道)类或代码,我不理解。所以我自己尝试了以下方法:

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

当我第一次运行这个代码时,我从我的tweet中得到了文本,但是当我刷新页面时,有时会得到以下错误:

警告: file_get_contents(http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries) [function. s]file-get-contents]: failed to open stream: HTTP请求失败!HTTP/1.0 400错误的请求在/path/to/file第88行

致命错误:未捕获异常' exception '与消息'String cannot parsed as XML'在/public/sites/www.singledays.nl/tmp/index.php:89堆栈跟踪:#0/public/sites/www.singledays.nl/tmp/index.php(89): SimpleXMLElement->__construct(") #1 {main}抛出/path/to/file第89行

第88行&

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

真的奇怪。有时有效,有时无效。

有人知道这个问题和/或解决方案吗?为什么错误似乎是随机发生的(尽管它现在已经出错了一段时间)?

谢谢!

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

就像每个人都说的那样,调试时你应该把结果缓存到文件中,如果下载失败,那么使用缓存,上面的代码会为你做。