如何将名称空间声明移到顶部?

时间:2013-09-29 20:50:45

标签: php xml simplexml

代码:

<?php
$ns = 'http://example.com';
$rss = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?>'.
                            '<rss/>');
$rss->registerXPathNamespace('example', $ns);
$rss->addAttribute('version', '2.0');
$rss->addChild('example:foo', '1', $ns);
$rss->addChild('example:bar', '2', $ns);
echo '<pre>'.htmlspecialchars($rss->asXML()).'</pre>';
?>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><example:foo xmlns:example="http://example.com">1</example:foo><example:bar xmlns:example="http://example.com">2</example:bar></rss>

期望的输出:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:example="http://example.com"><example:foo>1</example:foo><example:bar>2</example:bar></rss>

如何告诉SimpleXML将名称空间声明移至<rss/>

1 个答案:

答案 0 :(得分:1)

您应该将xmlns:example="http://example.com"添加到xml标签
试试这段代码:

<?php
$ns='http://example.com';
$rss=new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><rss xmlns:example="http://example.com"></rss>');
$rss->registerXPathNamespace('example',$ns);
$rss->addAttribute('version','2.0');
$rss->addChild('example:foo','1',$ns);
$rss->addChild('example:bar','2',$ns);

echo '<pre>'.htmlspecialchars($rss->asXML()).'</pre>';
?>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:example="http://example.com" version="2.0"><example:foo>1</example:foo><example:bar>2</example:bar></rss>