php:simplexml异常重试
我正在使用 SimpleXML 查询 API,该 API 偶尔会因未知原因而失败。我想让脚本重试最多 5 次。我该怎么做?我认为这与将对象包装在 try/catch 中有关,但我对此不太有经验——已尝试阅读有关异常处理的手册,但仍然不知所措。
感谢您的帮助:)
// set up xml handler
$xmlstr = file_get_contents($request);
$xml = new SimpleXMLElement($xmlstr);
这是我收到的错误消息:
[function.file-get-contents]: 无法打开流: HTTP 请求失败!
I am querying an API using SimpleXML which will occasionally fail for reasons unknown. I would like to have the script retry up to 5 times. How can I do this? I assume it has something to do with wrapping the object in a try/catch, but I'm not very experienced with this -- have tried to read the manual on exception handling but am still at a loss.
Thanks for any help :)
// set up xml handler
$xmlstr = file_get_contents($request);
$xml = new SimpleXMLElement($xmlstr);
Here is the error message I am receiving:
[function.file-get-contents]: failed to open stream: HTTP request failed!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 curl 获取您要解析的内容... file_get_contents 可以没有太多解释就失败了。也尽量不要使用@(这会隐藏可能导致应用程序死亡的错误),或者您可以使用错误的方式编码,因为您可以隐藏警告
try using curl to get the content you want to parse... file_get_contents can fail without much explanation about it. also try to dont use @ (this hide you errors that can make die the application) or you can just use to code in a wrong way just because you can hide the warnings
try .. catch
块不会捕获常规错误,而只会捕获Exception
,除非您设置set_error_handler
将错误转换为 < a href="http://www.php.net/manual/en/class.errorexception.php" rel="nofollow noreferrer">ErrorException
s. 看到问题出在在file_get_contents
中,类似这样的内容可能是一个更好的选择(未经测试):但是,由于您尝试从 http url 读取,我认为失败与 ini 设置有关是否允许 url 请求打开文件。请参阅allow_url_fopen
。是不是有什么人/什么人时不时地改变这个设置?
废话...这是极不可能的,因为它不能在运行时设置(即 PHP > 4.3.4)。
A
try .. catch
block will not catch regular errors, but onlyException
s, unless you set upset_error_handler
to have errors be translated toErrorException
s. Seeing that the problem lies in thefile_get_contents
something like this might be a better option (untested):However, since you are trying to read from a http url, I presume the failure has something to do with the ini setting on whether url requests are allowed for opening files. See the docs onallow_url_fopen
. Is something/someone altering this setting now and then perhaps?Scrap that... it's highly unlikely, since it can not be set at runtime (PHP > 4.3.4 that is).
您描述的使用
try ... catch
的一种示例方法。这并不是真正处理错误,而是重试 5 次。我建议尝试诊断导致间歇性故障的问题。您可能想再次抛出异常并在调用代码的更高处捕获它。
One example way of using
try ... catch
you describe. This isn't really dealing with the error but it retries 5 times. I'd recommend trying to diagnose the issue causing intermittent failures.You might want to throw the Exception again and catch it higher up the calling code.