Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML - Create element - New line

How can i create a new line in an element?

I do:

$currentTrack->appendChild($domtree->createElement('code', '    test1;
test2;
test3;'));

However it adds 
 to the end of every line. How can i get rid of that?

like image 789
TheNiceGuy Avatar asked Mar 22 '23 08:03

TheNiceGuy


1 Answers


 is the Carriage Return part of a \r\n style line ending. I think DOMDocument encodes it to preserve it. If you check the XML specification it says that it will get normalized to \n if not encoded.

So you have different options:

  1. Ignore the escaped entities, they get decoded in the xml parser
  2. Use CDATA-Elements, the normalization is not done here, so DOMDocument sees no need to escape the "\r".
  3. Make sure that you saved your file with \n style line endings
  4. Normalize the line endings to \n before creating the DOM

Here is some sample source to show the different behaviour:

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

Output:

<?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>
like image 168
ThW Avatar answered Mar 23 '23 22:03

ThW