1
<?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'};

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.