【问题标题】:Properly reading the data of .csv files in php正确读取php中.csv文件的数据
【发布时间】:2016-06-17 03:27:14
【问题描述】:

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

$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 文件时file("upload/payment.csv") 有什么问题?

2.) 读取适用于 csv 文件的最佳代码是什么? 系统,而不是更改整个代码。应该保留 foreach 循环。

3.) fgetcsv 对于现有代码是否更好?应该做出哪些改变?

【问题讨论】:

  • 我怀疑其失败的特定行存在问题,例如未正确终止。在文本编辑器中打开文件找到这些行,看看是否有什么奇怪的地方
  • @Dagon,也许我的 csv 文件中的某些字段是空的,有些字段带有逗号。
  • 好吧,如果分隔符中有逗号,您应该使用本机 csv 函数而不是自己滚动

标签: php file csv foreach


【解决方案1】:

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

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

【讨论】:

  • 如果我想使用 foreach 循环,你有参考吗?
猜你喜欢
  • 1970-01-01
  • 2020-03-11
  • 2022-01-01
  • 2022-11-13
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2017-01-23
相关资源
最近更新 更多