【问题标题】:PHP SimpleXML: Feed modificationPHP SimpleXML:提要修改
【发布时间】:2011-06-11 01:34:03
【问题描述】:

我想修改 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 可以吗? 谢谢。

【问题讨论】:

  • 我可以这样做来取消设置所有项目: unset($this->simpleXML->channel->item);这行得通!谢谢你。现在我只需要添加新项目。

标签: php rss simplexml feed nodes


【解决方案1】:

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

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" ?>

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

【讨论】:

  • 好的,很好。我想我没有完全理解你的问题,但它似乎对你有帮助:)
猜你喜欢
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 2012-02-06
  • 2011-02-23
  • 2011-06-20
相关资源
最近更新 更多