Proper reading of data .csv files in php

I have a working system on which I receive data from two CSV files. And save all the data in an array, and then compare some data available in both csv files. The system works well, but later I found out that some of the lines are not displayed in the array. I think that I am not using the correct code when reading the csv file. I want to change / improve the system. This is my code when reading or receiving data from a csv file.

$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 comaparing of datas... 

1.) What is wrong with file("upload/payment.csv") when reading a csv file?

2.) What is the best code when reading a csv file that is applicable to the system without changing the whole code. A foreach loop should remain.

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

0
source share
1 answer

Yes, for this purpose you can use "fgetcsv". The fgetcsv () function parses a string from an open file. This function returns the CSV fields in the array with success, or FALSE on failure and EOF. check the examples below

eg1:

 <?php $file = fopen("contacts.csv","r"); print_r(fgetcsv($file)); fclose($file); ?> 

e.g. 2:

 <?php $file = fopen("contacts.csv","r"); while(! feof($file)) { print_r(fgetcsv($file)); } fclose($file); ?> 

Link: https://gist.github.com/jaywilliams/385876

+1
source

All Articles