Properly reading the data of .csv files in php

2019-09-11 13:46发布

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.

$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 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?

1条回答
Juvenile、少年°
2楼-- · 2019-09-11 14:21

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

eg1 :

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

eg 2:

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

while(! feof($file))
{
 print_r(fgetcsv($file));
 }

fclose($file);
?>

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

查看更多
登录 后发表回答