如何在PHP中使用cURL读取XLSX文件?
我正在尝试在PHP中用cURL读取一个XLSX文件。文本文件可以正常读取,但每次尝试读取二进制文件时,返回的字节数为0,并且似乎也没有抛出错误。
下面是代码:
$sourceURL = 'https://www.gencon.com/downloads/events.xlsx';
$targetFilename = 'GenConEvents.xlsx';
if (file_exists($targetFilename))
{
unlink($targetFilename);
}
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $sourceURL);
$contents = curl_exec($c);
curl_close($c);
echo "File returned " . strlen($contents) . " bytes\n\n";
if (!file_put_contents($targetFilename, $contents))
{
echo "Error downloading the spreadsheet\n\n";
return;
}
返回的输出是:
File returned 0 bytes.
Error downloading the spreadsheet
我是不是漏掉了某些选项?
URL是有效的。
如果把 $sourceURL中的XLSX文件换成CSV或 HTML文件,它就能正常工作。另一方面,ZIP文件也有同样的0 字节问题。
解决方案
你的代码对二进制文件没有问题。CURLOPT_RETURNTRANSFER 不关心响应是文本、XLSX还是ZIP。
问题很可能出在服务器拒绝请求或重定向,并且你没有检查cURL的错误/状态码。
试试这个:
$c = curl_init($sourceURL);
curl_setopt_array($c, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_FAILONERROR => false,
CURLOPT_USERAGENT => 'Mozilla/5.0',
]);
$contents = curl_exec($c);
if ($contents === false) {
die('cURL error: ' . curl_error($c));
}
$httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($c, CURLINFO_CONTENT_TYPE);
curl_close($c);
echo "HTTP code: $httpCode\n";
echo "Content type: $contentType\n";
echo "File returned " . strlen($contents) . " bytes\n";
if ($contents === '' || $httpCode >= 400) {
die("Download failed\n");
}
file_put_contents($targetFilename, $contents);
重要的部分是:
CURLOPT_FOLLOWLOCATION => true
因为下载经常会被重定向,而且:
curl_error($c)
curl_getinfo($c, CURLINFO_HTTP_CODE)
因为 curl_exec() 可能返回空字符串,而你的代码看不到原因。
此外,不要使用这个检查:
if (!file_put_contents(...))
改用这个:
if (file_put_contents($targetFilename, $contents) === false)
因为 file_put_contents() 可能返回 0,并且 0 在PHP中被当作 false。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。