Hi I use the following PHP code to parse a twitter feed and display the latest two tweets in the footer of a website..
<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>
For some reason it seems to not always work and most of the time the following error is displayed..
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/fix开发者_Go百科edgearfrenzy.rss" in /home/fixedge1/public_html/catalog/view/theme/CartMania-Clean/template/common/footer.tpl on line 336
I can't work out why on earth it sometimes works and sometimes doesn't, any ideas??
The website is http://www.fixedgearfrenzy.co.uk and it's the twitter feed in the bottom right
IIRC, Twitter impose a per-hour limit on the number of times you can load a feed. If your results are intermittent, this is probably the reason why. Try caching the feed results locally to avoid re-loading the same data from Twatter over and over again.
You should 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...
精彩评论