1

代码:

<?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/>?

4

1 回答 1

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>
于 2013-09-29T22:02:41.783 回答