开发者

Filter a RSS flux by keywords in PHP

开发者 https://www.devze.com 2022-12-17 21:24 出处:网络
I have a little site in PHP (that is more static that dynamic, anyway). I see multiple sites publishes RSS fluxes or whatever the name is.

I have a little site in PHP (that is more static that dynamic, anyway). I see multiple sites publishes RSS fluxes or whatever the name is.

I wonder if there a possibility to load a such RSS flux, filter it by the site keywords theme and display it like a little thematic news 开发者_如何学Ccolumn using PHP.

Is this task complicated? With what should I start? I am completely new in the field, so sorry if such a questions are already answered.


Update: There were a few errors in this answer's code. Thanks to @obelizsk for identifying them, I've updated the answer since.

Given a RSS:


<rss version="2.0">
<channel>
<title>(Title)</title>
<description>(Description)</description>
<link>http://www.link.to/the/feed/</link>
<item>
<title> New RSS Creation Tool </title>
<description> FeedForAll generates rss feeds so webmasters do not need to struggle with feed creation </description>
<link> http://www.feedforall.com </link> 
<pubDate> Aug, 22 2004 00:12:30 EST </pubDate>
<category> software </category> 
</item>
</channel>
</rss>

You could scan the title, description and/or category tags for keywords you're interested in.

Let's say you have an array in your PHP script, i.e.

$keywords = array("php", "mysql", "open source");

Then, using SimpleXML you can parse the RSS feed:


function has_keywords($haystack, $wordlist)
{
  $found = false;
  foreach ($wordlist as $w)
  {
    if (stripos($haystack, $w) !== false) {
      $found = true;
      break;
    }
  }
  return $found;
}

$rss = simplexml_load_file("http://www.mywebsite.com/my/rss/feed/");
foreach ($rss->channel->item as $i)
{
  if (
      has_keywords($i->title, $keywords)
   || has_keywords($i->description, $keywords)
   || has_keywords($i->category)
  )
  {
    $news[] = array
    (
        "title" => $i->title,
        "description" => $i->description,
        "link" => $i->link
    );
  }
}

This will provide you with an array $news, populated with the data you've selected through the keyword check.

You can render this with any HTML code you want, by simply iterating through $news.

On a side note, you can also perform the same task with JavaScript and XMLHttpRequest, with no need of PHP intervention. Load the feed as an XML and go with the same procedure. To render the data, you can use document.createElement() to append the child nodes containing the information you've requested.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号