XML-创建元素-新行

The*_*Guy 3 php xml dom domdocument

如何在元素中创建新行?

我做:

$currentTrack->appendChild($domtree->createElement('code', '    test1;
test2;
test3;'));
Run Code Online (Sandbox Code Playgroud)

但是,它添加
到每行的末尾。我该如何摆脱呢?

ThW*_*ThW 5


\r\n样式行结尾的回车部分。我认为DOMDocument对其进行编码以保留它。如果检查XML规范,它说它将被标准化为\n未编码状态。

因此,您有不同的选择:

  1. 忽略转义的实体,它们在xml解析器中解码
  2. 使用CDATA-Elements,此处未进行规范化,因此DOMDocument认为无需转义“ \ r”。
  3. 确保您保存的文件以\n样式行结尾
  4. \n在创建DOM之前将行尾标准化为

这是一些示例源,以显示不同的行为:

$text = "test1;\r\ntest2;\r\ntest3;\r\n";

$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->appendChild($root = $dom->createElement('root'));

$root->appendChild(
  $node = $dom->createElement('code')
);
// text node - CR will get escaped
$node->appendChild($dom->createTextNode($text));

$root->appendChild(
  $node = $dom->createElement('code')
);
// cdata - CR will not get escaped
$node->appendChild($dom->createCdataSection($text));

$root->appendChild(
  $node = $dom->createElement('code')
);
// text node, CRLF and CR normalized to LF
$node->appendChild(
  $dom->createTextNode(
    str_replace(array("\r\n", "\r"), "\n", $text)
  )
);

$dom->formatOutput = TRUE;
echo $dom->saveXml();
Run Code Online (Sandbox Code Playgroud)

输出:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <code>test1;&#13;
test2;&#13;
test3;&#13;
</code>
  <code><![CDATA[test1;
test2;
test3;
]]></code>
  <code>test1;
test2;
test3;
</code>
</root>
Run Code Online (Sandbox Code Playgroud)