Page 1 of 1

Properly reading the data of .csv files

Posted: Thu Jun 16, 2016 11:08 pm
by xkevin
I have a working system on which I get the data of two .csv file. And save all the data into array and then compare some of the data existing on both csv file. The system works well but later I found out that some of the rows doesn't display on the array. I think I don't use the proper code in reading a csv file. I want to edit/improve the system. This is my code on reading or getting the data from csv file.

Code: Select all

$thedata = array(); 

$data = file("upload/payment.csv"); 

   foreach ($data as $deposit){ 

        $depositarray = explode(",", $deposit); 
        $depositlist = $depositarray; 

        $key = md5($depositlist[9] . $depositlist[10]); 

        $thedata[$key]['payment'] = array( 
        'name' => $depositlist[0], 
        'email' => $depositlist[1], 
        'modeofpayment' =>$depositlist[8], 
        'depositdate' => $depositlist[9], 
        'depositamount' => number_format($depositlist[10],2) 
    ); 
 } 

'<pre>',print_r($thedata),'</pre>'; 
//more code here for comparing of datas...
1.) What is wrong with file("upload/payment.csv") when reading csv file?

2.) What is the best code in reading a csv file that is applicable on the system, not changing the whole code. Should remain the foreach loop.

3.) Is fgetcsv much better for the existing code? What changes should be made?

Re: Properly reading the data of .csv files

Posted: Fri Jun 17, 2016 3:03 pm
by pickle
1) Nothing
2/3) Use fgetcsv(). It's a function specifically built to read in CSV files, and takes care of parsing escaping "", and all that jazz. It's just easier.