Remove new row from xml element value

I have an xml file containing 6000 elements such as LastName and FirstName.

I need to delete a new line inside an element value.

Input:

<info>
  <LastName>

     HOOVER

  </LastName>
</info>

Conclusion:

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

I tried preg_replace, and str_replacefor space and \n, \t, \rand failed.

+1
source share
1 answer

Since you are working with XML, you must also use one of the PHP XML extensions . The following example uses the DOM and XPath to find all text nodes in the XML document and trim.

Input signal:

$xml = <<< XML
<info>

  <LastName>

     HOOVER

  </LastName>

</info>
XML;

The 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();

Conclusion:

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

All Articles