phpsimplexmlsimplexmlrpcserver

reading the first value using simplexml


I am using simplexml to read all the child nodes successfully. But how do I read the "NumCrds"?

<ACCOUNT NumCrds="1">
<ACCNO>some Bank</ACCNO>
<CURRCODE>CAD</CURRCODE>
<ACCTYPE>00</ACCTYPE>
</ACCOUNT>

I have read it somewhere in the PHP manual but I am unable to find it now.

$my_num_cards=$sxe->ACCOUNT['NumCrds']; 

This is printing the number 1 for all the records even if there are values like 2, 3 in the file.


Solution

  • Attributes can be accessed using array indexes:

    $data = '<ACCOUNT NumCrds="1">
    <ACCNO>some Bank</ACCNO>
    <CURRCODE>CAD</CURRCODE>
    <ACCTYPE>00</ACCTYPE>
    </ACCOUNT>
    ';
    $xml = new SimpleXMLElement($data);
    
    // this outputs 1
    echo $xml['NumCrds'];
    

    It is also possible to use the SimpleXMLElement::attributes() function to returns a list of all of the attribute key/value pairs.

    $attributes = $xml->attributes();
    echo $attributes['NumCrds'];