正确读取php中的.csv文件的数据 [英] Properly reading the data of .csv files in php

查看:357
本文介绍了正确读取php中的.csv文件的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作系统,我得到两个.csv文件的数据。并将所有数据保存到数组,然后比较两个csv文件上存在的一些数据。系统工作良好,但后来我发现一些行不显示在数组上。我想我不使用正确的代码读取csv文件。我想编辑/改进系统。这是我从读取或从csv文件获取数据的代码。

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。)什么是当读取csv文件时,文件(upload / payment.csv)

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

2。)在读取一个适用于
系统的csv文件时,最好的代码是什么,而不是改变整个代码。应该保持foreach循环。

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。) fgetcsv 更好的现有代码?应该做什么改变?

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

推荐答案

是的,您可以使用fgetcsv
fgetcsv()函数解析打开的文件中的一行。该函数返回成功时数组中的CSV字段,或者失败和EOF时返回FALSE。
检查下面的示例

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);
?> 

例如2:

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

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

fclose($file);
?>

链接: https://gist.github.com/jaywilliams/385876

这篇关于正确读取php中的.csv文件的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆