user12636163
user12636163

Reputation:

read from one and write into second excel file - PHP

I have one excel file with a lot of data, this is an example of one row open in the editor:

"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",""

I have this code that works good with one condition

$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);

And as a result in the new file ive got row like this:

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",

The problem is when i open a new file in the editor, it doesnt have "" in the begining and in the end of values, and that is the problem, what i did wrong?

Upvotes: 1

Views: 471

Answers (1)

M.S
M.S

Reputation: 86

Your code looks good, you just need to put .csv at line $temp_table = fopen('write.csv','w'); because you're using fputcsv() function in the while loop. which is generating output based on csv file standards. if you get output in .txt format some columns would missing quotes "". In that case you need to handle this manually.

Edit

if you don't want to output it as csv than replace your code with the below updated code.

$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);

Upvotes: 2

Related Questions