3

Possible Duplicate:
Accessing @attribute from SimpleXML

I am using a few third party APIs which returns errors via xml in the following form:

<xml>
<status>0</status>
<error code="111">Error message text goes here.</error>
</xml>

Using simplexml_load_string in PHP I can easily get the status 0 and the error message text but I cannot find a means of retrieving the code="111" value from the <error code="111">. It seems to get dropped by SimpleXML.

<?php
    $bytesRead = file_get_contents('http://api.....');
    $xml = simplexml_load_string($bytesRead);

    echo '<pre>'; print_r($xml); echo '</pre>';
?>

Outputs

SimpleXMLElement Object
(
    [status] => 0
    [error] => Error message text goes here.
)

Am I missing something? Is there a way to obtain this value or can someone suggest another method to get this?

Community
  • 1
  • 1
JJ.
  • 5,425
  • 3
  • 26
  • 31

2 Answers2

11

It's there but just doesn't show in the print_r output. Like the basic examples page coins it in Example #5 Using attributes:

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

Example:

$x = '<xml>
<status>0</status>
<error code="111">Error message text goes here.</error>
</xml>';

$attributeObject = simplexml_load_string($x)->error['code'];

print_r($attributeObject);
print_r((string) $attributeObject);

Program Output (Demo)

SimpleXMLElement Object
(
    [0] => 111
)
111
hakre
  • 193,403
  • 52
  • 435
  • 836
Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
3

just use like this echo $xml->error['code'];

eg: http://codepad.org/uOqeBNz9

Noor Ahmed
  • 257
  • 1
  • 4