PHP如果file_get_contents失败,请改为执行此操作 [英] PHP If file_get_contents fails, do this instead

查看:337
本文介绍了PHP如果file_get_contents失败,请改为执行此操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有使用Free Bing转换程序API转换当前文本字符串的功能.我只想确定是否有任何故障或应用程序ID发生问题,或者我继续处理请求,我不希望显示大错误.

I have a function to translate the current text string using the Free Bing translator API. I just want to make sure if anything fails or something happens with the Application ID or I go over on requests, I don't want a big error to show.

我现在拥有的代码是:

$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$translate = simplexml_load_string($translate_feed);

return $translate[0];

我想发生的事情是什么都失败了,因此,如果我在URL中添加另一个字符以使其无效,那么我希望它只返回$text,以便至少显示 something .

What I want to happen is if anything fails, so if I add in another character to the URL to make it invalid then I want it to just return $text so at least something shows.

谢谢!

推荐答案

您是否尝试过故意使它失败以查看会发生什么情况?

Have you tried failing it on purpose to see what happens?

如果是例外情况,那就抓住并处理...

If it's an exception, just catch it and handle it...

try{
    //enter code to catch
}catch(Exception $ex){
    //Process the exception
}

如果函数输出错误,只需@隐藏错误并手动处理$ translate_feed或$ translate错误输出.

If there is an error outputted by the function, just @ to hide the error and handle the incorrect output of $translate_feed or $translate manually.

您可以尝试通过仅将无效的URI传递给file_get_contents,然后将非XML或无效的XML强制提供给simplexml_load_string来故意失败,以查看会发生什么情况.

You can try failing it on purpose by simply passing an invalid URI to file_get_contents and then forcefully feed non XML or invalid XML to simplexml_load_string to see what happens.

这篇关于PHP如果file_get_contents失败,请改为执行此操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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