Reputation: 15
<?xml version="1.0" encoding="UTF-8"?>
<abc-response>
<error-messages>
<errors code="302">
User does not have access to this Product
</errors>
</error-messages>
</abc-response>
am using simplexml_load_string and using the attribute function to get the code and I keep getting a null value.
$results = simplexml_load_string($response);
$errorCode = $results->attributes()->{'errors'};
Upvotes: 1
Views: 63
Reputation: 40886
You need to navigate to the element with the attribute you want. There are lots of ways.
echo $results->{'error-messages'}->errors['code'];//302
This works just fine since there's just one error-messages
and one errors
. If you had several, you could use array notation to indicate the one you want. So the line below also echoes 302
echo $results->{'error-messages'}[0]->errors[0]['code'];
You could even use xpath
, a query language to traverse xml. The //
will return all nodes by name:
echo $results->xpath('//errors')[0]->attributes()->code; //302
echo
shows a number, but it's still an object. If you'd like to capture just the integer, cast it like this:
$errorCode = (int) $results->{'error-messages'}->errors['code'];
Check out this really helpful intro.
Upvotes: 3