代码之家  ›  专栏  ›  技术社区  ›  Anuj TBE

php curl:保存到文件前检查响应是否有错误

  •  0
  • Anuj TBE  · 技术社区  · 6 年前

    我有一个curl脚本,当成功执行时,它返回二进制内容,我需要将其保存到一个文件(file.wav)。

    但是,在出现错误的情况下,它以JSON格式返回错误,如

    '{ "code" : 401 , "error" : "Not Authorized" , "description" : "..." } '
    

    我的卷发剧本就像

        $text_data = [
            'text' => $this->text
        ];
        $text_json = json_encode($text_data);
    
        $output_file = fopen($this->output_file_path, 'w');
    
        # url
        $url = $this->URL.'?voice='.$this->voice;
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERPWD, $this->USERNAME.':'.$this->PASSWORD);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: audio/'.$this->audio_format,
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $text_json);
        curl_setopt($ch, CURLOPT_FILE, $output_file);
        curl_setopt($ch, CURLOPT_HEADER, true);
    
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new Exception('Error with curl response: '.curl_error($ch));
        }
        curl_close($ch);
        fclose($output_file);
    
        $decode_result = json_decode($result);
    
        if (key_exists('error', $decode_result)) {
            throw new Exception($decode_result->description, $decode_result->code);
        }
    
        if ($result && is_file($this->output_file_path))
            return $this->output_file_path;
    
        throw new Exception('Error creating file');
    

    当结果成功时,这个方法很有效。但当出现错误时,错误消息也会保存到 output_file 因此,该文件是不可读的。

    在存储到文件之前,如何检查是否有任何错误?

        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($result, 0, $header_size);
        $body = substr($result, $header_size);
    
        debug($header_size);      // always prints `false`
        debug($header);           // ''
        debug($body);             // '1'
    

    1 回复  |  直到 6 年前
        1
  •  0
  •   chjortlund    6 年前

    在写入文件之前执行curl_getinfo()(不要在代码开头打开它)。

    $ch = curl_init('http://www.google.com/');
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $c = curl_exec($ch);
    
    if(curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200)
        echo "Something went wrong!";
    

    任何非200(成功)的响应代码都被视为错误,因为google.com已经上线,上面的代码很可能不会返回任何信息;)