簡體   English   中英

PHP curl:將響應保存到文件之前檢查錯誤

[英]PHP curl: check response for error before saving to file

我有一個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'

我嘗試檢查標頭響應,但即使成功,也總是錯誤的。 甚至頭信息也保存在外文件中。

在寫入文件之前執行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處於在線狀態,上述代碼很可能不會返回任何內容;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM