Remove newline from xml element value

落爺英雄遲暮 提交于 2019-12-11 13:37:25

问题


I have an xml file containing 6000 element like LastName and FirstName.

I need to remove new line inside element value.

Input:

<info>
  <LastName>

     HOOVER

  </LastName>
</info>

Output:

<info>
  <LastName>
     HOOVER
  </LastName>
</info>

I've tried preg_replace and str_replace for space and \n, \t, \r and failed.


回答1:


Since you are working with XML, you should also use one of the XML extensions PHP has to offer. The example below uses DOM and XPath to find all the text nodes in your XML document and trim them.

Input:

$xml = <<< XML
<info>

  <LastName>

     HOOVER

  </LastName>

</info>
XML;

Code:

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//text()') as $domText) {
    $domText->data = trim($domText->nodeValue);
}
$dom->formatOutput = true;
echo $dom->saveXml();

Output:

<?xml version="1.0"?>
<info>
  <LastName>HOOVER</LastName>
</info>


来源:https://stackoverflow.com/questions/8200582/remove-newline-from-xml-element-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!