simplexml_load_string loses the order of tags

限于喜欢 提交于 2019-12-12 01:52:59

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/29698192/simplexml-load-string-loses-the-order-of-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!