Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove starting and ending spaces from XML elements

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?

like image 273
Ella Avatar asked Oct 11 '22 01:10

Ella


1 Answers

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.

like image 195
ralphje Avatar answered Oct 12 '22 23:10

ralphje