【问题标题】:PHP is adding unwanted 
 in the outputPHP正在添加不需要的 在输出中
【发布时间】:2021-02-27 09:30:01
【问题描述】:

我想将文本区域的内容保存在 XML 中,但由于某种原因 PHP 在 XML 输出中添加了

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

我正在使用 nl2br() 函数,因为我想将换行符转换为 &lt;br&gt;,但为什么在输出中添加(或离开?)换行符 &amp;#xD;

示例输出:

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

【问题讨论】:

  • 这行不通,因为&lt;br&gt; 是一个标签。您需要使用CDATA

标签: php xml dom simplexml


【解决方案1】:

\&amp;#xD; 是回车,而不是换行。

无论如何,nl2br() 函数 inserts 换行符 在字符串中的换行符之前;它不会取代它们。

尝试使用:

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

或类似的东西而不是nl2br()

【讨论】:

    【解决方案2】:

    SimpleXMLElement 没有直接附加 xml 标签的能力。这意味着,您不需要的标签只是编码符号。但它可以在DOM 系列函数中直接附加 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();
    

    附:我没有运行这段代码,可能有一些错误。只是解决你问题的一个方向

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多