xml - PHP is adding unwanted 
 in the output
Get 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?
Example output:
<?xml version="1.0"?>
<products>
</product>
<product>
<description>mfgdgan<br />
1<br />
2<br />
3</description>
</product>
</products>
Answer
Solution:
\
is a carriage return, not a line feed.
Anyway, thenl2br()
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 ofnl2br()
.
Answer
Solution:
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 ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: please make sure the php redis extension is installed and enabled.
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.
Similar questions
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.