所以我有这个代码
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('CONFIG');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('APP-ID');
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('166533e56');
$subNode->appendChild($textNode);
$domDoc->save('config.xml');
生成
<CONFIG><APP-ID>166533e56</APP-ID></CONFIG>
这没有换行符。 当我添加
$domDoc->formatOutput = true;
就在代码的最后一行
之前$domDoc->save('config.xml');
输出现在很好:
<CONFIG>
<APP-ID>166533e56</APP-ID>
</CONFIG>
但是,当我在另一个php中尝试打开xml并在其中写入内容时,无论我尝试什么,它都会被无格式附加在那里。
在我做的另一个PHP代码中:
$domDoc = new DOMDocument;
$domDoc->load('config.xml');
$rootNode = $domDoc->documentElement;
$config_root = $rootNode->getElementsByTagName("CONFIG");
$rootElt = $domDoc->createElement('USER-ID');
$subNode = $rootNode->appendChild($rootElt);
$textNode = $domDoc->createTextNode('333265332f');
$subNode->appendChild($textNode);
$rootElt = $domDoc->createElement('USER-NAME');
$sub2Node = $rootNode->appendChild($rootElt);
$textNode = $domDoc->createTextNode('John');
$sub2Node->appendChild($textNode);
$domDoc->formatOutput = true;
$domDoc->save('config.xml');
导致
<CONFIG>
<APP-ID>166533e56</APP-ID>
<USER-ID>333265332f</USER-ID><USER-NAME>John</USER-NAME></CONFIG>
这是完全错误的。它应该是
<CONFIG>
<APP-ID>166533e56</APP-ID>
<USER-ID>333265332f</USER-ID>
<USER-NAME>John</USER-NAME>
</CONFIG>
为什么没有添加换行符?我做错了什么?
答案 0 :(得分:1)
在之前设置$domDoc->preserveWhiteSpace = false;
:您加载文件:
$domDoc = new DOMDocument;
$domDoc->preserveWhiteSpace = false;// <-- this line
$domDoc->loadXML(<<<XML
<?xml version="1.0"?>
<CONFIG>
<APP-ID>166533e56</APP-ID>
</CONFIG>
XML
);
$rootNode = $domDoc->documentElement;
$config_root = $rootNode->getElementsByTagName("CONFIG");
$rootElt = $domDoc->createElement('USER-ID');
$subNode = $rootNode->appendChild($rootElt);
$textNode = $domDoc->createTextNode('333265332f');
$subNode->appendChild($textNode);
$rootElt = $domDoc->createElement('USER-NAME');
$sub2Node = $rootNode->appendChild($rootElt);
$textNode = $domDoc->createTextNode('John');
$sub2Node->appendChild($textNode);
$domDoc->formatOutput = true;
//$domDoc->save('config.xml');
echo $domDoc->saveXML();