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 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多