PHP正在添加不需要的&#除息的;在输出中

PHP正在添加不需要的&#除息的;在输出中,php,xml,dom,simplexml,Php,Xml,Dom,Simplexml,我想用XML保存textarea的内容,但出于某种原因,PHP添加了 : <? $products = simplexml_load_file('data/custom.xml'); $product = $products->addChild('product'); $product->addChild('description', nl2br($_POST['description'])); //format XML output,

我想用XML保存textarea的内容,但出于某种原因,PHP添加了

<?
    $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>

SimpleXMLElement无法直接附加xml标记。这意味着,您不需要的标记只是编码符号。但是在函数家族中,可以直接附加xml标记。谢天谢地,在同一个XML文档上同时使用SimpleXML和DOM很容易

$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();
下面的示例使用文档片段向文档添加两个元素

$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();
另外,我没有运行这个代码,可能有一些错误。这只是解决您的问题的一个方向

\&xD是回车,不是换行符

无论如何,
nl2br()
函数在字符串中的换行符前面插入换行符;它不能取代它们

尝试使用:

str\u替换(数组(“\r\n”、“\r”、“\n”)、“
”)

或者用类似的方法代替
nl2br()

这将不起作用,因为

是一个标记。你需要使用。