PHP SimpleXML:Feed修改

时间:2011-01-18 12:07:22

标签: php rss simplexml feed nodes

我想修改RSS提要。我想从Feed中删除X项,然后以XML格式返回新的Feed。

<?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有可能吗? 谢谢。

1 个答案:

答案 0 :(得分: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" ?>

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