代码:
<?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/>
?