Reputation: 327
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)
Upvotes: 3
Views: 4300
Reputation: 1539
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
Upvotes: 4