使用PHPExcel,我想从互联网上读取一个文件。 PHPExcel库似乎只适合打开本地文件,而不是URL。这是我试过的:
<?php
require __DIR__ . '/vendor/autoload.php';
$string = file_get_contents('http://opendatakit.org/wp-content/uploads/static/sample.xls');
$stream = fopen('php://memory','r+');
fwrite($stream, $string);
rewind($stream);
$objPHPExcel = PHPExcel_IOFactory::load('php://memory');
这是我收到的错误:
致命错误:未捕获异常'PHPExcel_Reader_Exception' 消息'无法打开php://内存供阅读!文件没有 存在。“
我也尝试过直接传递网址(PHPExcel_IOFactory::load('http://opendatakit.org/wp-content/uploads/static/sample.xls')
)。类似的错误。
致命错误:未捕获异常'PHPExcel_Reader_Exception' 消息'无法打开 http://opendatakit.org/wp-content/uploads/static/sample.xls 读!文件不存在。'
编辑:还尝试了一个临时文件
$string = file_get_contents('http://opendatakit.org/wp-content/uploads/static/sample.xls');
$temp = tmpfile();
fwrite($temp, $string);
fseek($temp, 0);
$objPHPExcel = PHPExcel_IOFactory::load($temp);
这次出现不同的错误:
警告:pathinfo()期望参数1为字符串,给定资源 在/project/vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php中 在224行
警告:file_exists()期望参数1是有效路径, 给出的资源 /project/vendor/phpoffice/phpexcel/Classes/PHPExcel/Reader/Excel2007.php 在第81行
致命错误:未捕获异常'PHPExcel_Reader_Exception' 消息'无法打开资源ID#10进行阅读!文件没有 存在。“
答案 0 :(得分:2)
你的想法很好。但PHPExcel需要一个文件路径才能正常工作。 您可以尝试使用此示例:
$string = file_get_contents('http://opendatakit.org/wp-content/uploads/static/sample.xls');
$tmp = tempnam(sys_get_temp_dir(), "FOO");
file_put_contents($tmp, $string);
$objPHPExcel = PHPExcel_IOFactory::load($tmp);
//Perform all your operations
// ...
unlink($tmp);
请参阅PHP手册了解tempnam()