简体   繁体   English

PHP simplexml_load_file - 错误处理

[英]PHP simplexml_load_file - error handling

I'm loading a XML file from a foreign server which is working.我正在从正在运行的外部服务器加载 XML 文件。 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?我应该只显示“错误 - 请重新加载页面”之类的错误消息,还是应该直接将用户重定向到“主页”或 404 页面?

Thanks for tips.感谢您的提示。 (I've only found examples for files on the same server) (我只找到了同一服务器上文件的示例)

From looking at the php documentation of the function simplexml_load_file通过查看 function simplexml_load_file的 php 文档

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.我真的不知道你想从这个 XML 中得到什么,但是如果它第一次不起作用并且出现错误,那么告诉用户它不起作用有什么意义,请重新加载页面。

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我建议要么重定向到一个错误页面,比如 404,要么显示一条错误消息,比如“意外错误 - 请稍后再试”,然后让它记录到错误日志或 email 你告诉你错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM