您可以在文档中的所需位置写出命名空间一次,在顶部元素中写出 fe:
$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument('1.0');
$writer->startElement('sample');
$writer->writeAttributeNS('xmlns','foo', null,'http://foo.org/ns/foo#');
$writer->writeAttributeNS('xmlns','bar', null, 'http://foo.org/ns/bar#');
$writer->writeElementNS('foo','quz', null,'stuff here');
$writer->writeElementNS('bar','quz', null,'stuff there');
$writer->endElement();
$writer->endDocument();
$writer->flush(true);
这应该最终像
<?xml version="1.0"?>
<sample xmlns:foo="http://foo.org/ns/foo#" xmlns:bar="http://foo.org/ns/bar#">
<foo:quz>stuff here</foo:quz>
<bar:quz>stuff there</bar:quz>
</sample>
这是一种令人讨厌的 xmlwriter 不会跟踪这些声明 - 它允许您编写无效的 xml。需要属性也很烦人,即使它可以为 null - 而且它是第三个参数,而不是最后一个。
$2c, *-派克