我找到了一个很好的脚本来解析这里的推文源https://github.com/karlmonson/php-xml-twitter-feed/blob/master/php-xml-twitter-feed.php,但是我需要添加一个可自定义的限制来显示有多少RSS条目(例如3或5)。我该怎么做?我需要在哪里插入代码行?
我有一些其他PHP脚本使用如下行:
$ maxitems = 10; $ items = array_slice($ rss-> items,0,$ maxitems);
...但我不知道如何将其与下面的脚本结合起来。
非常感谢任何帮助或提示!
链接中的代码如下所示:
第1部分:
<?php
// Create the human readable "ago" time for each Tweet
function humanTiming ($time) {
// Get the current time set to GMT
$cur_date = strtotime(gmdate("M d Y H:i:s O"));
// Get the time since Tweet was tweeted
$time = $cur_date - $time;
// Set the tokens in seconds to calculate which "ago" string to return
$tokens = array (
31536000 => 'YEAR',
2592000 => 'MONTH',
604800 => 'WEEK',
86400 => 'DAY',
3600 => 'HOUR',
60 => 'MINUTE',
1 => 'SECOND'
);
// Count the seconds and return the "ago" string
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$returnValue = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'S':'');
return $returnValue;
}
}?>
第2部分:
<?php
// Set the feed url. Replace YourTwitterFeed with your Twitter Username
$feed = simplexml_load_file('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=YourTwitterFeed');
echo "<ul>";
if (isset($feed)) :
// Loop through each feed item and display each item as text with hyperlinks included.
foreach ( $feed->channel->item as $tweet ) :
// Get the date the Tweet was published
$pubDate = date(strtotime($tweet->pubDate));
// Get the text of the Tweet
$text = htmlspecialchars($tweet->description);
// Filter each Tweet to make clickable handles and links
$text = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1" rel="nofollow" target="_blank">$1</a>', $text);
$text = preg_replace('/@(\w+)/','<a href="http://twitter.com/$1" target="_blank">@$1</a>',$text);
$text = preg_replace('/\s+#(\w+)/',' <a href="http://search.twitter.com/search?q=%23$1" target="_blank">#$1</a>',$text);
// Get the human readable "ago" time
$humantime = humanTiming($pubDate);
// Return each Tweet in a list element
echo "<li>";
echo $text;
echo "<br />";
echo "<small><i>TWEETED " . $humantime . " AGO</i></small>";
echo "</li>";
endforeach;
else :
// Handler for an empty list of Tweets
echo '<li>No items.</li>';
endif;
echo "</ul>";
?>
非常感谢!
答案 0 :(得分:0)
$maxitems = 10;
foreach ( $feed->channel->item as $i => $tweet ) :
if ($i == $maxitems) {
break;
}
答案 1 :(得分:0)
如果在获取数据时无法限制,请参阅LimitIterator。
<?php
foreach ( new LimitIterator($feed->channel->item, 0, 10) as $tweet ) {
//do stuff
}