修改PHP脚本:从指定开放数据页面定位带export/get?id的最新下载链接并自动处理文件
最新数据集自动拉取改造PHP脚本
核心调整点
- 新增数据集官方页面请求逻辑,自动提取页面内第一个携带
export/get?id=参数的下载链接 - 自动补全协议相对链接的
https://前缀,生成完整可访问的下载地址 - 完全兼容原有下载、解压、重命名的存储流程
- 修复原有脚本遍历解压目录时未跳过
.、..系统目录的问题 - 新增模拟浏览器请求头,避免被目标站点拦截
运行前提
- 需确保PHP配置中
allow_url_fopen已开启,否则无法远程拉取页面和下载文件
完整代码
<?php // 目标数据集页面地址 $datasetPageUrl = 'https://data.mos.ru/opendata/61241/'; // 配置请求上下文,模拟浏览器UA避免被站点拦截 $context = stream_context_create([ 'http' => [ 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\r\n" ] ]); // 拉取数据集页面HTML内容 $pageContent = file_get_contents($datasetPageUrl, false, $context); // 正则匹配第一个携带export/get?id=参数的协议相对下载链接 preg_match('#//[^"\']*export/get\?id=\d+#', $pageContent, $matches); if (empty($matches)) { exit('未匹配到有效下载链接'); } // 补全HTTPS协议头得到完整下载地址 $downloadUrl = 'https:' . $matches[0]; function downloadJs($file_url, $save_to) { $content = file_get_contents($file_url); file_put_contents($save_to, $content); } // 执行ZIP文件下载 $savePath = realpath("./img/feeds") . '/61241.zip'; downloadJs($downloadUrl, $savePath); // 解压ZIP包 $zip = new ZipArchive; $zip->open($savePath); $zip->extractTo('./img/feeds/61241'); $zip->close(); // 遍历解压目录,将CSV文件重命名为指定文件名 $directory = './img/feeds/61241/'; if ($handle = opendir($directory)) { while (false !== ($fileName = readdir($handle))) { // 跳过系统默认目录项 if ($fileName == '.' || $fileName == '..') { continue; } rename($directory . $fileName, $directory . '61241.csv'); } closedir($handle); } echo "Ok!"; ?>
内容的提问来源于stack exchange,提问作者user404405
相关产品推荐
相关产品推荐

