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>

Upvotes: 1

Views: 271

Answers (2)

ocrdu
ocrdu

Reputation: 2183

\&#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().

Upvotes: 1

Urmat Zhenaliev
Urmat Zhenaliev

Reputation: 1547

SimpleXMLElement doesn't have the ability directly append xml tags. This means, that your unwanted tags is just encoded symbols. But it is available in the DOM family of functions to append xml tags directly. Thankfully, it is easy to work with SimpleXML and DOM at the same time on the same XML document.

The example below uses a document fragment to add a couple of elements to a document.

$products = simplexml_load_file('data/custom.xml');
$product = $products->addChild('product');
$description = $product->addChild('description');

$dom = dom_import_simplexml($description);

$fragment = $dom->ownerDocument->createDocumentFragment();
$fragment->appendXML(nl2br($_POST['description']));
$dom->appendChild($fragment);

echo $description->asXML();

P.S. I didn't run this code, there maybe some errors. It's just a direction to solve your issue

Upvotes: 0

Related Questions