0

我想修改一个 RSS 提要。我想从提要中删除 X 项,然后将新提要作为 XML 返回。

<?php
class RSS {
    private $simpleXML;

    public function __construct($address) {
        $xml = file_get_contents($address);
        $this->simpleXML = simplexml_load_string($xml);
    }

    private function getRssInformation() {
        // Here I want to get the Rss Head information ...
    }

    // Here I get X items ...
    private function getItems($itemsNumber, $UTF8) {
        $xml = null;
        $items = $this->simpleXML->xpath('/rss/channel/item');

        if(count($items) > $itemsNumber) {
            $items = array_slice($items, 0, $itemsNumber, true);
        }

        foreach($items as $item) {
            $xml .= $item->asXML() . "\n";
        }

        return $xml;
    }

    public function getFeed($itemsNumber = 5, $UTF8 = true) {
        // Here i will join rss information with X items ...
        echo $this->getItems($itemsNumber, $UTF8);
    }
}
?>

XPath 可以吗?谢谢你。

4

1 回答 1

0

另一种方法(但可能更清洁):

private function getItems($itemsNumber, $UTF8) {
    $xml = '<?xml version="1.0" ?>
                <rss version="2.0">
                    <channel>';

    $i = 0;

    if (count($this->simpleXML->rss->channel->item)>0){
        foreach ($this->simpleXML->rss->channel->item as $item) {
            $xml .= str_replace('<?xml version="1.0" ?>', '', $item->asXML());
            $i++;
            if($i==$itemsNumber) break;
        }
    }
    $xml .='  </channel></rss> ';

    return $xml;
}  

但我认为 asXML(); 添加 XML 声明:

<?xml version="1.0" ?>

我编辑了我的代码。它很脏,但它应该可以工作。有更好的主意吗?

于 2011-01-18T12:19:55.103 回答