PHP If file_get_contents fails, do this instead

后端 未结 7 1833
谎友^
谎友^ 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: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);
        }
    }
    

提交回复
热议问题