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