3

I'm loading a XML file from a foreign server which is working. But how do I receive an error message if the file does not exist or something else went wrong while loading it?

This is my code:

$xml = simplexml_load_file('http://api.example.com/2/image/' . $myhash . '.xml'); 

Also I'ld like to know what's the best practice if something like that happens. Should I just display an error message like "error - please reload page" or should I directly redirect the user like to the "homepage" or a 404 page?

Thanks for tips. (I've only found examples for files on the same server)

1 Answer 1

4

From looking at the php documentation of the function simplexml_load_file

You can just do this:

$xml = simplexml_load_file('http://api.example.com/2/image/' . $myhash . '.xml');
if ($xml === false) {
      // error so redirect or handle error
      header('location: /404.php');
      exit;
}
else {
     // process xml
}

I dont really know what you're trying to get from this XML, however if it doesnt work first time around and errors, then whats the point of telling the user that its not working, please reload the page.

I'd advise either redirecting to an error page such as 404 or display an error message saying something like "Unexpected error - please try again soon", then get it to either log to an error log or email you telling you of the error

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

4 Comments

More reason to use curl so that you can tell the difference between an HTTP Status: 500 or Status: 404.
By using your example I receive this error messages: Warning: simplexml_load_file - failed to open stream: HTTP request failed! and Warning: Cannot modify header information - headers already sent
@Michael: Prepend simplexml_load_file() with @ to suppress the warnings.
Thanky you very much! Working fine now.

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.