php - 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 文件中。
解决方案
在写入文件之前执行 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 已启动并在线;)
推荐阅读
- bash - 查找两个文件之间的所有匹配项,然后将字符附加到第二个文件中的所有匹配项的开头
- angular - 如何在 Angular 7 应用程序的 Edge 中查找错误源?
- powershell - 如何从批处理文件调用 powershell 脚本并将多个值返回到批处理文件?
- jquery - 用于 10-15 位电话号码验证的正则表达式
- umbraco - 母版页中的 Umbraco 字段
- google-apps-script - Data Studio Community Connector 始终需要授权
- android - 改造:小写标题
- python - 何时使用 paypal python sdk 完成付款?
- docker - 如何在 docker 容器中使用 Jenkins 工具安装?
- java - SharedPreferences.Editor apply() 失败