Search code examples
phpxmlsimplexmlsiblings

PHP: Xml with multiple sibling elements of the same name, maintain order


I have an xml file which looks something like this:

<items>
     <itemA/>
     <itemB/>
     <itemA/>
     <itemA/>
     <itemC/>
 </items>

but I need to process this using php and maintain the elements order. I understand how to access the elements with the same name using simplexml and array notation, but I cannot find a way to iterate through them all maintaining their order.


Solution

  • Select the parent element and iterate over its children, see http://php.net/manual/en/simplexmlelement.children.php

    $xml = new SimpleXMLElement(
    '<items>
         <itemA/>
         <itemB/>
         <itemA/>
         <itemA/>
         <itemC/>
     </items>');
    
    foreach ($xml->children() as $item) {
      //...
    }