0

所以我有这个代码

$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>

为什么没有添加换行符?我做错了什么?

4

1 回答 1

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();

现场演示

于 2013-02-21T10:11:12.363 回答