php从url检索xls到csv


php retrieve xls from url to csv

我想使用php来检索托管在网站上的xls文件。一旦我得到文件,我想转换成json/csv/tsv并将其保存在我的Web服务器上。

我找到了PHPExcel库,但我看到的所有示例都与本地文件有关。

<?php
require_once('Classes/PHPExcel.php');
$url = "http://www.website-example.com/dir/file.xls";
//Usage:
convertXLStoCSV($url,'output.csv');
function convertXLStoCSV($infile,$outfile)
{
    $fileType = PHPExcel_IOFactory::identify($infile);
    $objReader = PHPExcel_IOFactory::createReader($fileType);
    echo $infile;
    $objReader->setReadDataOnly(true);   
    $objPHPExcel = $objReader->load($infile);    
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
    $objWriter->save($outfile);
    echo $outfile;
}
?>

您可能需要将XLS文件的副本下载到服务器,然后使用PHP对其进行解析。

使用cURL(http://php.net/manual/en/book.curl.php)获取XLS文件内容:

<?php
    // create curl resource
    $ch = curl_init();
    // set url
    curl_setopt($ch, CURLOPT_URL, "somedomain.com/some-xls-file.xls");
    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // $output contains the output string
    $xlsData= curl_exec($ch);
    // close curl resource to free up system resources
    curl_close($ch);
?>

然后直接将$xlsData管道传输到PHPExcel,或者使用fwrite将XLS文件保存到服务器(http://php.net/manual/en/function.fwrite.php):

<?php
    $file = fopen($_SERVER['DOCUMENT_ROOT']. "/your-new-xls-file.xls", "w");
    echo fwrite($file, $xlsData);
    fclose($file);
?>