PHP If file_get_contents fails, do this instead

后端 未结 7 1791
谎友^
谎友^ 2021-01-02 12:23

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 Applicat

相关标签:
7条回答
  • 2021-01-02 13:00

    if( !$translate_feed) return "Failed";

    0 讨论(0)
  • 2021-01-02 13:07
    $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";
    }
    
    0 讨论(0)
  • 2021-01-02 13:09

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

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-02 13:12

    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.

    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.

    0 讨论(0)
  • 2021-01-02 13:13
    $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;
    
    0 讨论(0)
  • 2021-01-02 13:19

    You can do like this

    if(@file_get_contents("yourFilePath.txt")){
         echo "success";
    }
    
    0 讨论(0)
提交回复
热议问题