0
我想通過curl在php下載文件也得到標題。php curl下載文件並獲取標題
// handler
$h = fopen($filePath , 'w');
// curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_FILE, $h);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'getAllHeaders'));
$a = curl_exec($ch); // return false;
curl_close($ch);
fclose($h);
public function getAllHeaders($ch, $header)
{
// check for 200 ok
if (preg_match('/HTTP[\/\.0-9\s\t]+200[\s\t]+OK/i', $header)) {
// header 200 found
$this->header200 = true;
}
// grab all headers keys and values
preg_match('/^(?P<key>[a-z0-9\-]+)\:(?P<value>.*)$/i', $header, $matches);
// cycle
foreach ($matches as $key => $value) {
if (!is_numeric($key)) {
$this->headers[strtolower(trim($key))] = trim($value);
}
}
// headers
return $this->headers;
}
但我不能得到標題和文件不能下載。我該如何解決這個問題。
什麼不起作用?請更多信息。另外,如果使用'CURLOPT_RETURNTRANSFER'轉儲它,curl的響應是什麼? 你調試了你的'getAllHeaders'方法來檢查它是否被調用,如果是,用哪個參數? –
我想你錯誤地使用了'CURLOPT_HEADERFUNCTION'。這個選項從你的函數讀取頭文件。它不會將收到的標題傳遞給它。檢查[文檔](http://www.php.net/curl_setopt)。你可以使用'CURLOPT_WRITEHEADER'來處理它。 –