Reputation: 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.
Upvotes: 1
Views: 3400
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.
$xml = <<< XML
<info>
<LastName>
HOOVER
</LastName>
</info>
XML;
$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();
<?xml version="1.0"?>
<info>
<LastName>HOOVER</LastName>
</info>
Upvotes: 7