[英]How to download csv file from the download link in php?
我想從此鏈接下載csv文件:
https://www.nasdaq.com/investing/etfs/etf-finder-results.aspx?download=Yes
但是這兩種代碼也不起作用。
$url = 'https://www.nasdaq.com/investing/etfs/etf-finder-results.aspx?download=Yes';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$str = curl_exec($curl);
echo $str;
和
$table = file_get_contents('https://www.nasdaq.com/investing/etfs/etf-finder-results.aspx?download=Yes');
請告訴我為什么此代碼在此鏈接中不起作用。 謝謝!
$file_name = 'ETFList.csv';
$url = 'https://www.nasdaq.com/investing/etfs/etf-finder-results.aspx?download=Yes';
function downloadFile($url, $filename)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible ; Googlebot/2.1 ; +http://www.google.com/bot.html)');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
if (curl_errno($ch)) die(curl_error($ch));
curl_close($ch);
$file = fopen($filename, 'wb');
fwrite($file, $data);
fclose($file);
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Transfer-Encoding: binary');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Content-Length: ' . filesize($filename));
readfile($filename);
}
}
downloadFile($url, $file_name);
$file = 'ETFList.csv'; $url = 'https://www.nasdaq.com/investing/etfs/etf-finder-results.aspx?download=Yes'; function downloadFile($url, $filename) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $data = curl_exec($ch); curl_close($ch); header('Content-Description: File Transfer'); header('Content-Type: text/csv'); header("Content-Disposition: attachment; filename=\"$filename\""); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($data)); readfile($data); } downloadFile($url,$file);
php.ini文件中有一行可以取消注釋;
;user_agent="PHP"
或者,您可以在代碼中臨時設置它。
ini_set('user_agent', "PHP");
$table = file_get_contents('https://www.nasdaq.com/investing/etfs/etf-finder-results.aspx?download=Yes');
這是因為您使用的是https。 請參閱如何使用php通過https下載文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.