You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP请求特殊URL获取CSV并保存至服务器问题求助

解决PHP请求指定URL下载CSV文件失败的问题

这类ASPX接口通常会校验请求的User-Agent等请求头,仅允许浏览器发起的请求,这就是你用常规方法失败的原因。以下是可行的解决方案:

方案一:使用CURL(推荐,兼容性更强)

CURL可以灵活设置请求头,模拟浏览器行为:

<?php
// 目标URL
$url = 'http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx?h=0&r=0';
// 本地保存路径,比如服务器根目录下的client_type.csv
$savePath = './client_type.csv';

// 初始化CURL
$ch = curl_init($url);
// 设置CURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 模拟Chrome浏览器的User-Agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36');
// 跟随重定向(如果有的话)
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// 执行请求
$csvContent = curl_exec($ch);
// 检查错误
if(curl_errno($ch)) {
    die('CURL请求错误:' . curl_error($ch));
}
// 关闭CURL
curl_close($ch);

// 将内容保存到服务器文件
if(file_put_contents($savePath, $csvContent)) {
    echo 'CSV文件已成功保存到 ' . $savePath;
} else {
    echo '保存文件失败,请检查服务器权限';
}
?>

方案二:使用file_get_contents配合请求上下文

如果服务器开启了allow_url_fopen,也可以通过设置请求上下文来模拟浏览器:

<?php
$url = 'http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx?h=0&r=0';
$savePath = './client_type.csv';

// 设置请求头,模拟浏览器
$context = stream_context_create([
    'http' => [
        'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n"
    ]
]);

// 获取内容
$csvContent = file_get_contents($url, false, $context);
if($csvContent === false) {
    die('获取CSV内容失败');
}

// 保存文件
if(file_put_contents($savePath, $csvContent)) {
    echo 'CSV文件已成功保存到 ' . $savePath;
} else {
    echo '保存文件失败,请检查服务器权限';
}
?>

你之前代码的问题:

  1. file_put_contents的第一个参数应该是本地服务器的保存路径,不是目标URL;
  2. 没有设置请求头,导致服务器拒绝了非浏览器的请求;
  3. fopen的使用缺少错误处理,且同样没有请求头设置。

内容的提问来源于stack exchange,提问作者chrome chrome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:30:53