PHP 如果 file_get_contents 失败,请改为执行此操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8673272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:14:17  来源:igfitidea点击:

PHP If file_get_contents fails, do this instead

php

提问by Drew

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.

我有一个使用 Free Bing 翻译器 API 翻译当前文本字符串的函数。我只是想确保应用程序 ID 是否出现任何故障或出现问题,或者我继续处理请求,我不想显示大错误。

The code I have right now is:

我现在拥有的代码是:

$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];

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 $textso at least somethingshows.

我想要发生的是如果有任何失败,所以如果我在 URL 中添加另一个字符以使其无效,那么我希望它只是返回$text所以至少显示一些东西

Thanks!

谢谢!

回答by Mathieu Dumoulin

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
}

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.

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

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.

您可以通过简单地将无效的 URI 传递给 file_get_contents,然后将非 XML 或无效的 XML 强制提供给 simplexml_load_string 以查看会发生什么,从而故意尝试使其失败。

回答by Wes Crow

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


if ( $translate_feed === false )
{
   echo "failed";
}

回答by Azam Alvi

You can do like this

你可以这样做

if(@file_get_contents("yourFilePath.txt")){
     echo "success";
}

回答by Botyk

/*
It's a modified file_get_contents()
get_contents(filename, use_include_path, context, offset, maxlen)
*/
function get_contents($url, $u = false, $c = null, $o = null) {
    $headers = get_headers($url);
    $status = substr($headers[0], 9, 3);
    if ($status == '200') {
        return file_get_contents($url, $u, $c, $o);
    }
    return false;
}

echo get_contents('https://batas.kz/');

回答by Max

there is $http_response_headervariable is being created in local scope that we can use it to check headers returned from server. Here is my implementation:

$ http_response_header被在本地范围,我们可以用它来检查从服务器返回的头创建的变量。这是我的实现:

public function getData($url)
{
    try {
        $response = @file_get_contents($url);
        if (isset($http_response_header)) {
            if (!in_array('HTTP/1.1 200 OK', $http_response_header) &&
                !in_array('HTTP/1.0 200 OK', $http_response_header)) {
                throw new \Exception('Server did not return success header!');
            }
        }
        return $response;
    } catch (\Exception $ex) {
        throw new TransportException($ex->getMessage(), $ex->getCode(), $ex);
    }
}

回答by Eugen Rieck

$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$result=$text;
if ($translate_feed) {
  $translate = simplexml_load_string($translate_feed);
  if (is_array($translate)) $result=$translate[0];
}
return $result;

回答by Niet the Dark Absol

if( !$translate_feed) return "Failed";

if( !$translate_feed) return "Failed";