您好我使用以下PHP代码解析Twitter提要并在网站页脚中显示最新的两条推文..
<ul id="twitter_update_list" style="word-wrap:break-word;">
<?php
$doc = new DOMDocument();
$doc->load('http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss');
$arrFeeds = array();
$count = 0;
foreach ($doc->getElementsByTagName('item') as $node)
{
if($count < 2)
echo('<li><span style="word-wrap:break-word;">'.substr($node->getElementsByTagName('description')->item(0)->nodeValue, 17).' </span><a href="'.$node->getElementsByTagName('link')->item(0)->nodeValue.'">'.substr($node->getElementsByTagName('pubDate')->item(0)->nodeValue, 0, 16).'</a></li>');
$count = $count + 1;
}
?></ul>
出于某种原因,它似乎并不总是有效,并且大部分时间都会显示以下错误..
Warning: DOMDocument::load(http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss) [domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/fixedge1/public_html/catalog/view/theme/CartMania-Clean/template/common/footer.tpl on line 336Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss" in /home/fixedge1/public_html/catalog/view/theme/CartMania-Clean/template/common/footer.tpl on line 336
我无法弄清楚为什么它有时会起作用,有时却没有,任何想法?
网站为http://www.fixedgearfrenzy.co.uk,右下角是推特供稿
答案 0 :(得分:1)
IIRC,Twitter对每次加载Feed的次数施加了每小时限制。如果您的结果是间歇性的,这可能就是原因。尝试在本地缓存Feed结果,以避免反复从Twatter重新加载相同的数据。
答案 1 :(得分:0)
你应该use a valid user-agent
when using DOMDocument
to load a remote resource。
<?php
// Set a valid user-agent
$opts = array(
'http' => array(
'user_agent' => 'PHP libxml agent',
)
);
$context = stream_context_create($opts);
libxml_set_streams_context($context);
$doc = new DOMDocument();
$doc->load('http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss');
$arrFeeds = array();
// rest of your code...