1

I am using SimpleXML to load a response from an API call. However, if the server returns an error, it only returns a single XML tag with the error message:

<err>ERROR MESSAGE HERE</err>

I'm currently using this code to parse the API response:

$parsedresponse = simplexml_load_string($response);

The $parsedresponse variable contains only the error message. However, I need a way to check if the <err> tag is present so I know if there was an error. I can't seem to figure out how to do this...

Thank you!

2
  • It might be easier to check the response for <err> before loading it into simple XML. Commented Jan 23, 2013 at 19:00
  • OK - that's what I was thinking to. But I still can't quite figure out how to determine if it's in the raw response. I've tried if (!empty($response->err)) etc but that doesn't seem to do anything.... Commented Jan 23, 2013 at 19:05

2 Answers 2

1

If err tag is the root tag use the following condition to trace the error.

if ($parsedresponse->getName()=='err'){
    // got it
}

If its the first child use

if (isset($parsedresponse->err)){
    // got it
}
  • negate the condition as necessary.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I just tried this code but PHP fails with this: Fatal error: Can't use method return value in write context
@Jason Oops. It'd be == instead of =. Writing from iPad, so missed it. See the update
0
<?php

$xml = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<err>ERROR MESSAGE HERE</err>
EOF;

$sxml = simplexml_load_string($xml);

if ($sxml->getName() != "err") print('not set');
else print('set');

?>

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.