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.
Gordon
source share