Daniel Benedykt
Daniel Benedykt

Reputation: 6553

simplexml_load_string loses the order of tags

I have the following XML:

<mobapp>    
    <form>
        <input type="text" name="target" id="target" value="" maxlength="8" required="true" pattern="[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"/>
        <label for="target"> Phone number</label> 
        <input type="number" name="amount" id="amount" min="0" maxlength="16" required="true"/> 
        <label for="amount"> Amount to load:</label> 
    </form> 
</mobapp>

When I use simplexml_load_string($theXML) I get the following:

object(SimpleXMLElement)#150 (3) {
  ["input"]=>
  array(2) {
    [0] => object(SimpleXMLElement)#146 (1) {
      ["@attributes"]=> [... removed for brevity ...]
    }
    [1] => object(SimpleXMLElement)#146 (1) {
      ["@attributes"]=> [... removed for brevity ...]
    }
}
["label"]=>
  array(2) {
    [0] => [... removed for brevity ...]
    [1] => [... removed for brevity ...]

}

(I removed all the attributes to make it simpler to understand)

So I get an array of 2 "input" and an array of 2 "label", but I don't know the order in which they were in the XML.

Is there a way to get that order?

Upvotes: 0

Views: 206

Answers (1)

IMSoP
IMSoP

Reputation: 97718

So I get an array of ...

No, you don't. SimpleXML is an object, not an array; what's more, it's an object designed to be used as an API, not one with fixed properties. When you use print_r, var_dump, or anything like that, it represents itself as though it's an object with a bunch of arrays inside, but that's not actually what is happening.

The reason it shows that, is that if you access $simplexml_object->input, you can loop through all the <input> elements, in the order they appear, which is often useful.

However, to loop through all the elements, regardless of their tag name, use the ->children() method and then check the name of each using the ->getName() method, e.g.:

foreach ( $simplexml_object->children() as $node ) { 
    $tag_name = $node->getName();
    $text_content = (string)$node;
}

Upvotes: 5

Related Questions