Avoiding Errors When Attempting to Load an Unavailable File
Using php I want to load XML files from several websites and want to prevent err开发者_Go百科ors if my one of the sites is down. I'm using this code to access the URL.
function get_xml($url){
$xmlDoc = new DOMDocument();
$xmlDoc->load($url); // This is the line causing errors
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
...
If there is no xml feed available at $url I get lots of error messages like:
Warning: DOMDocument::load(): Space required after the Public Identifier
Warning: DOMDocument::load(): SystemLiteral " or ' expected
Warning: DOMDocument::load(): SYSTEM or PUBLIC, the URI is missing
Warning: DOMDocument::load(): Opening and ending tag mismatch: link line 5 and head
What can I do to prevent $url from attempting to load if the feed isn't available? I've tried:
if(file_exists($url)){
$xmlDoc->load('$url');
}
And things with fopen and @load but I could well have been using them incorrectly.
In theory (and if I remember correctly), you should be able to catch those errors (so you call deal with them yourself, instead of having them displayed) using the libxml1 functions.
I'm especially thinking about libxml_use_internal_errors()
:
libxml_use_internal_errors()
allows you to disable standard libxml errors and enable user error handling.
1.libxml
being the library that's using internally by DOMDocument
-- and SimpleXML
, btw
Try with:
if (!@$xmlDoc->load($url)){
return FALSE;
}
Your function get_xml
will return immediately FALSE
if the method load
fails to load the XML data
精彩评论