Search code examples
phpxmlsimplexml

Simple XML read element namespace attribute


I have an XML, schema below

$xml = 
'<NodeSet
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://opcfoundation.org/UA/2008/02/Types.xsd">
    <Node category="category" i:type="ObjectNode">
        <NodeId>
            <Identifier>i=86</Identifier>
        </NodeId>
    </Node>
</NodeSet>';

I need to extract the i:type attribute value from the Node element. I have tried accessing it as i would do it when accessing normal attributes but it seems it doesn't work that way

Here is how i can access the category attribute,

$xml=simplexml_load_string($xml);
echo $xml->Node[0]['category']; //this prints 'category' as expected
echo $xml->Node[0]['i:type']; //prints nothing, how do i get the i:type attribute value ?

Solution

  • You need to access the attributes with the namespace, this can be done using the attributes() method...

    echo $xml->Node[0]->attributes("i",true)['type'];
    

    Using ("i",true) says use the i prefix rather than having to put the URI.