尝试加载不可用的文件时避免错误 [英] Avoiding Errors When Attempting to Load an Unavailable File

查看:55
本文介绍了尝试加载不可用的文件时避免错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用php,我想从多个网站加载XML文件,并且如果我的一个网站宕机了,希望防止错误。我正在使用此代码访问URL。

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);
 ...

如果$ url上没有xml feed,我会得到很多错误消息,例如:

If there is no xml feed available at $url I get lots of error messages like:

警告:DOMDocument :: load():公共标识符后所需的空间

Warning: DOMDocument::load(): Space required after the Public Identifier

警告:DOMDocument :: load():SystemLiteral或'预期

Warning: DOMDocument::load(): SystemLiteral " or ' expected

警告:DOMDocument :: load():SYSTEM或PUBLIC,URI丢失

Warning: DOMDocument::load(): SYSTEM or PUBLIC, the URI is missing

警告:DOMDocument :: load():开始和结束标记不匹配:链接第5行和头部

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');
}

带有fopen和@load的东西,但我很可能一直没有正确使用它们。

And things with fopen and @load but I could well have been using them incorrectly.

推荐答案

尝试:

if (!@$xmlDoc->load($url)){
  return FALSE;
}

您的函数 get如果方法 load 无法加载XML数据,_xml 将立即返回 FALSE

Your function get_xml will return immediately FALSE if the method load fails to load the XML data

这篇关于尝试加载不可用的文件时避免错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆