首页 > 解决方案 > PHP curl:在保存到文件之前检查错误响应

问题描述

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

但是,如果出现错误,它会以 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,因此该文件不可读。

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

编辑 2:检查响应标头

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

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

标签: phpphp-curl

解决方案


在写入文件之前执行 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 已启动并在线;)


推荐阅读