【发布时间】:2017-04-20 15:39:58
【问题描述】:
我需要从这个网站下载一个压缩的 .csv 文件。 http://www.phrfsocal.org/web-lookup-2/该文件是右侧表格上方的下载数据链接。 问题是链接是动态创建的。所以我需要先把它提取出来。
当我将该链接粘贴到新的浏览器选项卡中时,浏览器会下载包含我感兴趣的 csv 的 zip 文件。
但是,当使用 CURL 尝试获取 zip 时,它会获取链接下方表格的 html。似乎无法弄清楚如何获取 .zip。 下面是我的代码,第一部分找到了链接,似乎可以正常工作。
第二部分是我遇到麻烦的地方。
PS 我已获得此页面所有者的许可,可以使用 Cron 作业每晚下载此数据。 提前致谢, 戴夫
$url = "http://www.phrfsocal.org/web-lookup-2/";
// url to the dynamic content doesn't seem to change.
$url = "https://b6.caspio.com/dp.asp?AppKey=0dc330000cbc1d03fd244fea82b4";
$header = get_web_page($url);
// Find the location of the Download Data link and extract the href
$strpos = strpos($header['content'], 'Download Data');
$link = substr($header['content'], $strpos, 300);
$link = explode(" ", $link);
$link = explode('"', $link[2]);
$url1 = $link[1];
print_r($url1);
print "<p>";
// Now Go get the zip file.
$zipFile = "temp/SoCalzipfile.zip"; // Local Zip File Path
$zipResource = fopen($zipFile, "w+");
// Get The Zip File From Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FILE, $zipResource);
$page = curl_exec($ch);
if (!$page) {
echo "Error :- " . curl_error($ch);
}
curl_close($ch);
echo "zip file recieved";
/* Open the Zip file */
$zip = new ZipArchive;
$extractPath = "temp";
if ($zip->open($zipFile) != "true") {
echo "Error :- Unable to open the Zip File";
}emphasized text
/* Extract Zip File */
$zip->extractTo($extractPath);
$zip->close();
【问题讨论】:
标签: php curl web-scraping zip