1

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
user1054508
  • 25
  • 1
  • 6
  • 1
    possible duplicate of [Remove starting and ending spaces from XML elements](http://stackoverflow.com/questions/7337992/remove-starting-and-ending-spaces-from-xml-elements) – Gordon Nov 20 '11 at 10:10
  • 1
    note that while this question is technically a duplicate the linked duplicate doesnt have an accepted answer and the given solutions are only soso in quality. maybe the linked one should be closed with this one instead. – Gordon Nov 20 '11 at 11:52
  • This question asks to partially retain whitespace so that the indentation is not broken. The duplicate questions seems to be interested in more common XML whitespace normalization that is more than just a `trim` on the content (but not much more thanks to the *any whitespace character* `\s` in PCRE and it's utf-8 mode), see [a DOM based answer there](http://stackoverflow.com/a/31793566/367456). – hakre Aug 03 '15 at 18:03

1 Answers1

7

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>
Gordon
  • 312,688
  • 75
  • 539
  • 559