How can I remove all spacing characters before and after a XML field?
<data version="2.0">
<field>
1
</field>
<field something=" some attribute here... ">
2
</field>
</data>
Notice that spacing before 1 and 2 and 'some attribute here...', I want to remove that with PHP.
if(($xml = simplexml_load_file($file)) === false) die();
print_r($xml);
Also the data doesn't appear to be string, I need to append (string) before each variable. Why?
You may want to use something like this:
$str = file_get_contents($file);
$str = preg_replace('~\s*(<([^>]*)>[^<]*</\2>|<[^>]*>)\s*~','$1',$str);
$xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
I haven't tried this, but you can find more on this at http://www.lonhosford.com/lonblog/2011/01/07/php-simplexml-load-xml-file-preserve-cdata-remove-whitespace-between-nodes-and-return-json/.
Note that the spaces between the opening and closing brackets (<x> _space_ </x>
) and the attributes (<x attr=" _space_ ">
) are actually part of the XML document's data (in contrast with the spaces between <x> _space_ <y>
), so I would suggest that the source you use should be a bit less messy with spaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With