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

PHP curl: check response for error before saving to file

我有一个 curl 脚本,成功执行后 returns 我需要将其保存到文件中的二进制内容 (file.wav)。

但是,如果出错,它会 returns 错误 json 格式,如

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

我的 curl 脚本就像

    $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,因此该文件不可读。

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

Edit 2: check response headers

    $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'

我尝试检查 header 响应,但即使成功也总是错误的。甚至 header 信息都保存在 outfile 文件中。

在写入文件之前执行 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(成功)的响应代码都被视为错误,上面的代码很可能不会 return 任何东西,因为 google.com 已启动并在线 ;)