Avoiding Errors When Attempting to Load an Unavailable File

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 10:29:02

问题


Using php I want to load XML files from several websites and want to prevent errors 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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/6800623/avoiding-errors-when-attempting-to-load-an-unavailable-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!