Properly reading the data of .csv files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xkevin
Forum Newbie
Posts: 14
Joined: Thu Jun 09, 2016 9:01 pm

Properly reading the data of .csv files

Post 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?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Properly reading the data of .csv files

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply