Properly reading the data of .csv files in php

有些话、适合烂在心里 提交于 2020-01-17 05:35:10

问题


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:


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



来源:https://stackoverflow.com/questions/37872628/properly-reading-the-data-of-csv-files-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!