Search code examples
phpxmldomsimplexml

PHP is adding unwanted 
 in the output


I would like to save the content of a textarea in XML, but for some reason PHP is adding 
 in the XML output:

<?
    $products = simplexml_load_file('data/custom.xml');
    $product = $products->addChild('product');
    $product->addChild('description', nl2br($_POST['description']));

    //format XML output, simplexml can't do this
    $dom                     = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput       = true;

    $dom->loadXML($products->asXML());
    file_put_contents('data/custom.xml', $dom->saveXML());

?>

<textarea class="form-control" id="description" name="description" placeholder="Description" rows="4"></textarea>

I am using the nl2br() function, because I want to convert new line characters to <br>, but why it is adding (or leaving?) a new line char &#xD; in the output?

Example output:

<?xml version="1.0"?>
<products>
  </product>
  <product>
    <description>mfgdgan&lt;br /&gt;&#xD;
1&lt;br /&gt;&#xD;
2&lt;br /&gt;&#xD;
3</description>
  </product>
</products>

Solution

  • \&#xD; is a carriage return, not a line feed.

    Anyway, the nl2br() function inserts line breaks in front of newlines in a string; it doesn't replace them.

    Try using:

    str_replace(array("\r\n", "\r", "\n"), "<br/>")
    

    or something similar instead of nl2br().