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

时间:2018-06-18 09:28:43

标签: php php-curl

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

但是,如果出现错误,它会以json格式返回错误,如

<a href="#" data-toggle="tooltip" title="Hooray!">Hover over me</a>
<script>
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip(); 
});
</script>

我的卷曲脚本就像

'{ "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'); ,因此该文件不可读。

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

  

编辑2:检查回复标题

output_file

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

1 个答案:

答案 0 :(得分:0)

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

相关问题