猿问

从一个读取并写入第二个excel文件 - PHP

我有一个包含大量数据的 excel 文件,这是在编辑器中打开一行的示例:


"A","001270","3755","TRIPP LITE MASTER-POWER","UPS EXTERNAL BATTERY PACK TOWER","12/24V APS INVERTER CHARGERS","0000000000000421.20","BP-260","000019.80","0037332080011","0015.00","0014.00","0019.50","","0000000000000222.80","0000000000000000.00","N","","UPS-C","BATT","0101","","N","","00000000000000.0000","2 YEAR LTD",""

我有这段代码在一种情况下效果很好


$table = fopen('read.csv','r');

$temp_table = fopen('write','w');

while (($data = fgetcsv($table)) !== FALSE){

    if(in_array($data[1],$spec)){ // this is if you need the first column in a row

        continue;

    }

    fputcsv($temp_table,$data);

}

fclose($table);

fclose($temp_table);

结果在新文件中我得到了这样的行:


A,001270,3755,"TRIPP LITE MASTER-POWER","UPS EXTERNAL BATTERY PACK TOWER","12/24V APS INVERTER CHARGERS",0000000000000421.20,BP-260,000019.80,0037332080011,0015.00,0014.00,0019.50,,0000000000000222.80,0000000000000000.00,N,,UPS-C,BATT,0101,,N,,00000000000000.0000,"2 YEAR LTD",

问题是当我在编辑器中打开一个新文件时,它在值的开头和结尾都没有“”,这就是问题所在,我做错了什么?


SMILET
浏览 72回答 1
1回答

慕码人8056858

您的代码看起来不错,您只需要放在.csvline 上$temp_table = fopen('write.csv','w');,因为您fputcsv()在 while 循环中使用函数。它基于 csv 文件标准生成输出。如果您以.txt格式获得输出,则某些列会缺少引号""。在这种情况下,您需要手动处理。编辑如果您不想将其输出为 csv 而不是用以下更新的代码替换您的代码。$table = fopen('read.csv','r');$temp_table = fopen('write.txt','w');while (($data = fgetcsv($table)) !== FALSE){    $data = '"'. implode('","', $data) .'"'; // this line will add the comma and double quote to each array value and wrap the string with double quote.    fputs($temp_table,$data);}fclose($table);fclose($temp_table);
随时随地看视频慕课网APP
我要回答