在电子邮件中捆绑RSS

时间:2012-02-24 05:02:55

标签: php rss simplepie

我一直在使用以下代码来提取Google新闻,但是,我需要在网站上将最终结果作为实际的RSS Feed,以便其他人可以获取Feed。现在输出创建一个很好的index.php页面。那很好,但不适合我的目的。 SimplePie可以创建一个格式化为rss输出的页面以用于抓取目的吗?

提前谢谢。


<?php

// Make sure SimplePie is included. You may need to change this to match the location of simplepie.inc.
require_once('simplepie.inc');

// We'll process this feed with all of the default options.
$feed = new SimplePie();

// Set the feed to process.
$feed->set_feed_url('http://news.google.com/news?hl=en&gl=us&q=new+york+commercial+real+estate&ie=UTF-8&output=rss');

// Run SimplePie.
$feed->init();

// This makes sure that the content is sent to the browser as text/html and the UTF-8 character set (since we didn't change it).
$feed->handle_content_type();

// Let's begin our XHTML webpage code.  The DOCTYPE is supposed to be the very first thing, so we'll keep it on the same line as the closing-PHP tag.
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Sample SimplePie Page</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

</head>
<body>

        <div class="header">
        <h2><a href="<?php echo $feed->get_permalink(); ?>"><?php echo $feed->get_title(); ?></a></h2>
        <p><?php echo $feed->get_description(); ?></p>
    </div>

    <?php
    /*
    Here, we'll loop through all of the items in the feed, and $item represents the current item in the loop.
    */
    foreach ($feed->get_items() as $item):
    ?>

        <div class="item">
            <h4><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>
            <p><?php echo $item->get_description(); ?></p>
            <p><small>Posted on <?php echo $item->get_date('j F Y | g:i a'); ?></small></p>
        </div>

    <?php endforeach; ?>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

SimplePie仅用于解析阶段,您需要编写自己的代码以将其输出为RSS。

你可以用快速而肮脏的方式做到这一点:

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
    <channel>
        <title>Your Site</title>

<?php
        foreach ($feed->get_items() as $item):
?>
        <entry>
            <title><?php echo $item->get_title() ?></title>
            <description><?php echo $item->get_content() ?></description>
            <!-- ... -->
        </entry>
    </channel>
</rss>

更好的方法是使用SimpleXML创建元素,然后输出结果。这将确保您的XML格式正确,并确保所有内容都能正确转义。

然而,正如布拉德所说,你在做这件事时也必须小心服务条款。你应该至少确保正确的归属。