用wordpress读取csv文件 [英] read csv file with wordpress
问题描述
如何使用 wordpress 读取 csv 文件,我尝试了下面的代码,但它不起作用:
How to read a csv file with wordpress, i tried the code below but it's not working:
require_once("PHPexcel/PHPExcel.php");
$file = "sample.csv";
$excelReader = PHPExcel_IOFactory::createReaderForFile($file);
$excelObj = $excelReader->load($file);
$workSheet = $excelObj->getSheet(0);
$lastRow = $workSheet->getHighestRow();
for ($row=2; $row <=$lastRow ; $row++) {
$col1 = $workSheet->getCell('A'.$row)->getValue();
var_dump($col1);
}
我在单独的 php 文件中尝试了这个,它可以工作,但是当我把它放在 wordpress 中时,它不再工作了,我得到了一个错误:致命错误:未捕获的 PHPExcel_Reader_Exception:无法打开 sample.csv 进行读取!文件不存在.
I tried this in separated php file and it works, but when i put it in wordpress, it's not working anymore and i got an error: Fatal error: Uncaught PHPExcel_Reader_Exception: Could not open sample.csv for reading! File does not exist.
推荐答案
对我来说这有效.并记住一件事
for me this worked . and remember one thing
将您的 csv 保存为 CSV (MS-DOS) (*.csv)
格式,然后尝试以下代码
save your csv into
CSV (MS-DOS) (*.csv)
format and then try following code
这里是我的 csv 数据示例
And here example of my csv data
NAME;ADDRESS;ZIP;CITY;TELEPHONE;SPONSOR;URL
global $wpdb;
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$handle = fopen($filename, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($handle)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$client_data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
fclose($handle);
// var_dump($cols);
$table_name = $wpdb->prefix . 'rlist';
foreach ($client_data as $client_row){
if (is_array($client_row)) {
foreach ($client_row as $value) {
$savedata = explode(";", $value);
if(!empty($savedata)){
$savedata[0] = ($savedata[0]) ? $savedata[0] : null;
$savedata[1] = ($savedata[1]) ? $savedata[1] : null;
$savedata[2] = ($savedata[2]) ? $savedata[2] : null;
$savedata[3] = ($savedata[3]) ? $savedata[3] : null;
$savedata[4] = ($savedata[4]) ? $savedata[4] : null;
$savedata[5] = ($savedata[5]) ? $savedata[5] : null;
$savedata[6] = ($savedata[6]) ? $savedata[6] : null;
$wpdb->insert(
$table_name,
array(
'NAME' => $savedata[0],
'ADDRESS' => $savedata[1],
'ZIP' =>$savedata[2],
'CITY' =>$savedata[3],
'TELEPHONE' =>$savedata[4],
'SPONSOR' =>$savedata[5],
'URL'=> $savedata[6]
)
);
}
}
}
}
fclose($file);
这里是这段代码的工作输出.
and here is working output of this code.
这篇关于用wordpress读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!