Loop through an XML object with SimpleXML

前端 未结 2 464
抹茶落季
抹茶落季 2020-11-29 11:42

I am trying to use SimpleXML in PHP to loop through a XML object - the object format is below:-

I get the following error when I try to get the element tags by name

2条回答
  •  一生所求
    2020-11-29 12:12

    I don't want to spoil the existing answer as it is answering correct an in a general fashion.

    For your concrete requirements as with your XML there aren't any attributes and you're just looking for the element-name => node-value pairs here, there is one function that comes to mind in conjunction with SimpleXMLElement here: get_object_vars.

    It is useful whenever you convert an object into an array and as SimpleXMLElement turns element names into object property names and the node-values as those property values it's pretty straight forward here:

    $xml     = simplexml_load_string($buffer);
    
    $items   = $xml->products->item;
    
    $devices = array_map('get_object_vars', iterator_to_array($items, FALSE));
    
    print_r($devices);
    

    The output is as suggested in the existing answer. And the online demo is here: https://3v4l.org/iQKQP

    You will likely able to achieve similar results with casting to arrays (if not exactly the same with SimpleXML), however in this case as I wanted to map it, I needed a true function.

    There is also the json-en- and -de-code doubling for converting complete trees, which comes in handy here, too:

    $xml     = simplexml_load_string($buffer);
    
    $items   = $xml->products;
    
    $devices = json_decode(json_encode($items), TRUE)['item'];
    

    The output then again is exactly as the existing answer. And the online demo again is here: https://3v4l.org/ToWOs

    Hope this is helpful and widens the view a bit.

提交回复
热议问题