我使用php DOMDocument
创建并保存XML
文件。
这是我的代码
$doc = new DOMDocument();
$document = $doc->createElement('DOCUMENT');
$document->nodeValue = '';
$doc->appendChild($document);
$order = $doc->createElement('ORDER');
$order->nodeValue = '';
$doc->appendChild($order);
$ele = $doc->createElement('Reportvariable1');
$ele->nodeValue = '';
$doc->appendChild($ele);
$ele = $doc->createElement('Reportvariable1');
$ele->nodeValue = '';
$doc->appendChild($ele);
$ele = $doc->createElement('Reportvariable1');
$ele->nodeValue = '';
$doc->appendChild($ele);
$ele = $doc->createElement('Reportvariable1');
$ele->nodeValue = '';
$doc->appendChild($ele);
$doc->appendChild($ele);
$doc->save('order_xml/Order_.xml');
它的输出很简单:
<?xml version="1.0"?>
<DOCUMENT></DOCUMENT>
<ORDER></ORDER>
<Reportvariable1></Reportvariable1>
<Reportvariable1></Reportvariable1>
<Reportvariable1></Reportvariable1>
<Reportvariable1></Reportvariable1>
如何创建这样的嵌套节点?
<?xml version="1.0"?>
<DOCUMENT>
<ORDER>
<Reportvariable1></Reportvariable1>
<Reportvariable1></Reportvariable1>
<Reportvariable1></Reportvariable1>
<Reportvariable1></Reportvariable1>
</ORDER>
</DOCUMENT>
答案 0 :(得分:2)
将您的代码更改为: -
$doc = new DOMDocument();
$document = $doc->createElement('DOCUMENT');$document->nodeValue = '';$doc->appendChild($document);
$order = $doc->createElement('ORDER');$order->nodeValue = '';$document->appendChild($order);
$ele = $doc->createElement('Reportvariable1');$ele->nodeValue = '';$order->appendChild($ele);
$ele = $doc->createElement('Reportvariable1');$ele->nodeValue = '';$order->appendChild($ele);
$ele = $doc->createElement('Reportvariable1');$ele->nodeValue = '';$order->appendChild($ele);
$ele = $doc->createElement('Reportvariable1');$ele->nodeValue = '';$order->appendChild($ele);
$doc->save('order_xml/Order_.xml');
您将获得所需的输出
答案 1 :(得分:1)
使用3个步骤向DOM添加新节点。
appendChild()
将节点附加到父级(文档或元素) appendChild()
返回节点。所以你可以嵌套create*
电话。
不要设置DOMElement::$nodeValue
。它需要特殊的逃避。创建文本节点并附加它会更安全。
$dom = new DOMDocument();
$document = $dom->appendChild(
$dom->createElement('DOCUMENT')
);
$order = $document->appendChild(
$dom->createElement('ORDER')
);
for ($i = 1; $i < 5; $i++) {
$reportVariable = $order->appendChild(
$dom->createElement('Reportvariable1')
);
// add some text content
$reportVariable->appendChild(
$dom->createTextNode('some text content' . $i)
);
}
$dom->formatOutput = true;
echo $dom->saveXml();
输出:
<?xml version="1.0"?>
<DOCUMENT>
<ORDER>
<Reportvariable1>some text content1</Reportvariable1>
<Reportvariable1>some text content2</Reportvariable1>
<Reportvariable1>some text content3</Reportvariable1>
<Reportvariable1>some text content4</Reportvariable1>
</ORDER>
</DOCUMENT>