dsft8327 2013-06-11 13:21
浏览 61
已采纳

使用SimpleXmlElement创建RSS提要的xmlns命名空间重定义错误?

I am trying to use PHP to create an XML document that will be used for an RSS feed. I've got it working for the most part, but I am getting a error on line 2 at column 29: redefinition of the xmlns prefix is forbidden while attempting to add an attribute with a namespace to my document.

I've tried the accepted answer here: Add rss xmlns namespace definition to a php simplexml document? but that changes the first line to <rss... instead of <xml...

Here is the code that I am working with:

<?php
$xml = new SimpleXMLElement('<xml vesion="1.0" />');
$rss = $xml->addChild('rss');
$rss->addAttribute('version','2.0');
$rss->addAttribute("xml:base",'http://intranet/bapm/rss-avd','xml');
$rss->addAttribute('xmlns:dc',"http://purl.org/dc/elements/1.1/",'xmlns');
....

the line that adds the xml:base attribute works fine, but when I add the line that adds the xmlns:dc attribute I get the error. If I don't add the 'xmlns' as the third argument, I get no errors, but the rendered attribute omits the namespace?

  • 写回答

2条回答 默认 最新

  • dshdb64088 2013-06-11 13:54
    关注

    The error message:

    redefinition of the xmlns prefix is forbidden

    is because xmlns is defined in XML (all names starting with the letters XML regardless of case are reserved), so you can not use "xmlns" as prefix. However in your code you use it as prefix:

    $rss->addAttribute('xmlns:dc', "http://purl.org/dc/elements/1.1/", 'xmlns');
                        #####                                           #####
    

    It is just not possible to add such attributes. Remove that line of code and the error goes away. Add the namespace declaration to the string when you create the new object, as shown in the accepted answer to "Add rss xmlns namespace definition to a php simplexml document?".

    To make this chrystal clear: You can not use SimpleXMLElement::addAttribute() to make an XML namespace declaration.


    Edit: SimpleXML was originally not designed to handle XML Namespaces and not all functionality is easily accessible (or straight-forward). The probably most clean way is using the sister library DOMDocument ("DOM").

    For a more detailed review how to add Namespace Declarations in SimpleXML please see the following existing Q&A material here on the Stackoverflow site:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据