Share XML in PHP

I have merged xml with the root element and several children of the element. Something like that

<root> <item>test1</item> <item>test2</item> </root> 

What I want is an easy way to parse xml and create an array of xml strings from elements.

 $arrXml[0] = '<item>test1</item>'; $arrXml[1] = '<item>test2</item>'; 

I am looking for an elegant solution, not any solution.

+6
xml php
source share
3 answers

Well, as mentioned in the comments on your question, I'm not sure if this is really what you should do , but since I cannot approve SimpleXml and I don't want people to think about it the only way, here's how to do it

with the DOM :

 $arrXml = array(); $dom = new DOMDocument; $dom->loadXML( $xml ); foreach( $dom->getElementsByTagName( 'item' ) as $item ) { $arrXml[] = $dom->saveXML( $item ); } print_r( $arrXml ); 

with XMLReader :

 $arrXml = array(); $reader = new XmlReader; $reader->xml( $xml ); while( $reader->read() ) { if( $reader->localName === 'item' && $reader->nodeType === 1 ) { $arrXml[] = $reader->readOuterXml(); } } print_r( $arrXml ); 

and XMLParser* :

 xml_parse_into_struct(xml_parser_create(), $xml, $nodes); $xmlArr = array(); foreach($nodes as $node) { if($node['tag'] === 'ITEM') { $arrXml[] = "<item>{$node['value']}</item>"; } } print_r($arrXml); 

* This can also be accomplished with callbacks called when an ITEM element is encountered. There will be more code, but rather flexible.

Please note that all of the above may require some tweaking depending on your real XML.


Given that the XML in your question (which is most likely just an example) is simple and straightforward to use, you can also use explode() :

 $arrXml = array_map( 'trim', array_filter( explode( PHP_EOL, $xml ), function( $line ) { return substr( $line, 0, 6 ) === '<item>'; } )); print_r( $arrXml ); 

or Regex (read below)

 preg_match_all('#<item>.*</item>#', $xml, $arrXml); print_r($arrXml[0]); 

Disclaimer Now, to make sure that you are not starting to parse XML with regular expressions or Explode regularly: the last two approaches are only possible if your markup is really clearly defined as you show it.

+7
source share

There are some good code examples in the comments of the SimpleXml manual page . I'm sure you can do something from the objectsIntoArray() sample.

+2
source share

Have you looked at SimpleXML ?

For example:

 $string = " <root> <item>test1</item> <item>test2</item> </root> "; $xml = simplexml_load_string($string); 
+1
source share

All Articles