Search code examples
phpxmlxml-parsingsimplexml

simplexml_load_string get attributes


The source XML is:

<attributeGroup id="999" name="Information">
   <attribute id="123" name="Manufacturer">Apple</attribute>
   <attribute id="456" name="Model">iPhone</attribute>  
</attributeGroup>

Code:

$xml = simplexml_load_string($xml);
print_r($xml);

output:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 999
            [name] => Information
        )

    [attribute] => Array
        (
            [0] => Apple
            [1] => iPhone
        )

)

How do I also get it to return the labels of attribute id and name?


Solution

  • You can access it like this using attributes property:

    $x = simplexml_load_string($xml);
    $g = $x->attributeGroup;
    foreach($g->xpath("//attribute") as $attr){
        var_dump((string)$attr->attributes()->id);
        var_dump((string)$attr->attributes()->name);
        var_dump((string)$attr); // for text value
    }