如何使用DOM计算我的Twitter Feed中的项目总数?

时间:2011-08-03 14:42:41

标签: php dom twitter rss

如何使用DOM计算我的Twitter Feed中的项目总数?

当我的Feed小于3时,下面的代码会导致错误 - 我该如何解决?

<?php
$xml = ("http://twitter.com/statuses/user_timeline/321998072.rss"); //http://twitter.com/statuses/friends_timeline/321998072.rss
$xmlDoc = new DOMDocument();
$xmlDoc -> load($xml);

# get elements from "<channel>"
$channel = $xmlDoc -> getElementsByTagName('channel') -> item(0);
$channel_title = $channel -> getElementsByTagName('title') -> item(0) -> childNodes -> item(0) -> nodeValue;
$channel_link = $channel -> getElementsByTagName('link') -> item(0) -> childNodes -> item(0) -> nodeValue;
$channel_desc = $channel -> getElementsByTagName('description') -> item(0) -> childNodes -> item(0) -> nodeValue;

# output elements from "<channel>"
/*
echo("<p><a href='" . $channel_link
  . "'>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");
*/
?>

<h4 class="heading-24dot">Twitter Updates</h4>

<p class="item-twitter channel-title"><a href="<?php echo $channel_link;?>" target="_blank" class="hover-opacity-04"><?php echo $channel_title;?></a></p>
<?php

# get and output "<item>" elements
$x = $xmlDoc -> getElementsByTagName('item');

for ($i=0; $i<=2; $i++)
{
    $item_title = $x -> item($i) -> getElementsByTagName('title') -> item(0) -> childNodes -> item(0) -> nodeValue;
    $item_link = $x -> item($i) -> getElementsByTagName('link') -> item(0) -> childNodes -> item(0) -> nodeValue;
    $item_date = $x -> item($i) -> getElementsByTagName('pubDate') -> item(0) -> childNodes -> item(0) -> nodeValue;
    $item_desc = $x -> item($i) -> getElementsByTagName('description') -> item(0) -> childNodes -> item(0) -> nodeValue;

    # NOTE: use this code for the server runs PHP5.3
    # DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    $date = new DateTime($item_date);

    # change the date format into Y-m-d H:i:s
    $item_date = $date -> format('Y-m-d H:i:s');

    # count time ago from the published date
    $time_ago = time_ago($date -> format('Y-m-d H:i:s'),'d M Y \a\t H:i');
?>
<p class="item-twitter"><a href="<?php echo $item_link;?>" target="_blank" class="hover-opacity-06"><?php echo preg_replace('/^(GingerMonkey_TL:)/', ' ',$item_desc);?></a><br/><span class="date-twitted-ago"><?php echo $time_ago;?></span></p>    
<?php
}
?>

1 个答案:

答案 0 :(得分:2)

$xpath = new DOMXPath($xmlDoc);
$count = $xpath->evaluate('count(//item)');