curl - 如何使用 curl 下载 IP2Location 数据库
问题描述
我正在尝试使用他们提供的 curl 命令从 IP2Location 下载数据库。我已注册,所以我有一个有效的令牌。他们给出的命令是
curl -o {LOCAL_FILE_NAME} "https://www.ip2location.com/download?token={DOWNLOAD_TOKEN}&file={DATABASE_CODE}"
这是我正在使用的代码,除了我的令牌:
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://www.ip2location.com/download?token={mytoken}&file={DB1LITEBIN}");
$dbfile = curl_exec($curl);
if (curl_errno($curl)) {
echo 'err '.curl_errno($curl);
}
curl_close($curl);
$file = 'db_download.bin';
$mode = 'w';
if (($fp = fopen($file , $mode))) {
$fout = fwrite($fp, $dbfile);
fclose($fp);
}
该脚本运行没有错误,但下载的文件只是他们网站的未找到页面。如果我在浏览器中使用 url,我会找不到相同的页面。有人可以指出我的错误吗?
解决方案
请尝试以下方法。请注意,您将下载一个包含 bin 文件的 zip 文件。
<?php
//The resource that we want to download.
$fileUrl = 'https://www.ip2location.com/download?token=XXXXXXXXXX&file=DB1LITEBIN';
//The path & filename to save to.
$saveTo = 'db_download.zip';
//Open file handler.
$fp = fopen($saveTo, 'w+');
//If $fp is FALSE, something went wrong.
if($fp === false){
throw new Exception('Could not open: ' . $saveTo);
}
//Create a cURL handle.
$ch = curl_init($fileUrl);
//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);
//Timeout if the file doesn't download after 20 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//Execute the request.
curl_exec($ch);
//If there was an error, throw an Exception
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
//Get the HTTP status code.
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Close the cURL handler.
curl_close($ch);
//Close the file handler.
fclose($fp);
if($statusCode == 200){
echo 'Downloaded!';
} else{
echo "Status Code: " . $statusCode;
}
推荐阅读
- react-native - 如何将数据发送到硬件上的先前路线按反应导航 5
- mongodb - MongoDB 存储 API 调用
- c# - 在 Blazor 中绑定使用 InputFile 选择的文件
- php - Opencart htaccess 以减少服务器响应时间和缓存
- android-layout - Xamarin.Android:水平滚动条不适用于 SfPulltoRefresh
- swift - 无法转换“SharedSequence”类型的值
' 到预期的参数类型 - apache-kafka - 如何在不使用 Docker 或 Windows Server 2016 上的 Confluent 平台的情况下在 Kafka 中设置 Debezium SQL Server 连接器?
- javascript - 强制 Facebook 使用风格
- android - 如何在片段布局中创建微调器?
- python - 使用 pdf2image 从目录中提取 pdf 并将图像输出到不同的目录