【问题标题】:SimpleXML fetch tag incl. all child-elementsSimpleXML 提取标签包括。所有子元素
【发布时间】:2011-10-01 10:29:27
【问题描述】:

我想用 simplexml 解析一个 rss 文件。如果我打印特定标签,则仅选择直接内容 - 不包括子标签和“子”标签。如何访问标签,包括。子标签名称及其内容?

//load rss into $xml
foreach ($this->xml->channel->item as $item) {
  echo "<h3>{$this->out($item->title)}</h3>",
       $this->out($item->description);
}

【问题讨论】:

    标签: php xml rss tags simplexml


    【解决方案1】:

    您可以使用 $this->xml->children() 来获取子节点,然后递归地使用它。我最近编写了一种方法,可以将一个 XML 块递归地复制到另一个中 - 它应该向您展示您可以使用的技术。

    protected function copyXml(SimpleXMLElement $from, SimpleXMLElement $to)
    {
        // Create a new branch in the target, as per the source
        $fromValue = (string) $from;
        if ($fromValue)
        {
            $toChild = $to->addChild($from->getName(), (string) $from);
        }
        else
        {
            $toChild = $to->addChild($from->getName());
        }
    
        // Copy attributes across
        foreach ($from->attributes() as $name => $value)
        {
            $toChild->addAttribute($name, $value);
        }
    
        // Copy any children across, recursively
        foreach ($from->children() as $fromChild)
        {
            $this->copyXml($fromChild, $toChild);
        }
    }
    

    HTH。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 2020-02-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      相关资源
      最近更新 更多