phpxmlsimplexmlcxml

How can I access the last attribute of an XML element using SimpleXML?


I am using SimpleXML to parse through a cXML document. I can't figure out how to access an attribute from the deepest element in the document. When I parse for the attribute "currency" in the xml snippet below it doesn't exist. I figured out that this only occurs on the deepest elements. Is there a way that I can parse this document using SimpleXML?

Example portion of an XML document I am attempting to parse.

<ItemOut name="ItemOut">
<ItemDetail name="ItemDetail">
    <UnitPrice name="UnitPrice">
        <Money currency="USD">12.99</Money>
    </UnitPrice>
</ItemDetail>

I have tried using the json encode/decode way...

$simpleXml=simplexml_load_string($xml);
$json = json_encode($simpleXml);
$xmlArray = json_decode($json,TRUE);

and using SimpleXML object...
$xmlObject = new SimpleXMLElement($xml);

Here is a picture of the array structure of the parsed document.


Solution

  • I think you need to run

    <?php
    $xmlObject = new SimpleXMLElement($xml);
    $currency = $xmlObject-> ItemDetail -> UnitPrice -> Money -> attributes() -> currency;
    ?>
    

    That will read your currency attribute and return EUR in your case