user1054508
user1054508

Reputation: 25

Remove newline from xml element value

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.

Upvotes: 1

Views: 3400

Answers (1)

Gordon
Gordon

Reputation: 317217

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>

Upvotes: 7

Related Questions