xml - PHP is adding unwanted
in the outputGet the solution ↓↓↓
I would like to save 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 nl2br() function, because I want to convert new line characters to
<br>, but why it is adding (or leaving?) new line char
in the output?
<?xml version="1.0"?> <products> </product> <product> <description>mfgdgan<br />
3</description> </product> </products>
is a carriage return, not a line feed.
nl2br() function inserts line breaks in front of newlines in a string; it doesn't replace them.
str_replace(array("\r\n", "\r", "\n"), "<br/>")
or something similar instead of
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
Share solution ↓
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 7.3.0".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.