【问题标题】:Reading *.csv files from directory and showing the content of each file fails从目录中读取 *.csv 文件并显示每个文件的内容失败
【发布时间】:2015-06-18 23:07:04
【问题描述】:

我在阅读文件夹和打开/输出 csv 数据方面需要帮助,我使用了其他人编写的示例,但没有一个对我有用。

我目前拥有的是这个,但它不输出文件:

$files = scandir($PathToCreate.$version."/"); //scan the folder
foreach($files as $file) { //for each file in the folder

//The following is another example I found but does not output anything I just need to open each file and be able to output / target specific data

$csv = array();
$lines = file($file, FILE_IGNORE_NEW_LINES);

foreach ($lines as $key => $value)
{
    $csv[$key] = str_getcsv($value);
} 
print_r($csv)

}

【问题讨论】:

  • 你的 csv 文件有什么分隔符?
  • “他们都没有工作”没有帮助。你有什么问题?
  • 它使用逗号分隔信息
  • 你现在得到什么输出,你期望什么?
  • 顺便说一句:看看fgetcsv()函数:php.net/manual/en/function.fgetcsv.php

标签: php csv fgetcsv opencsv scandir


【解决方案1】:

这应该适合你:

(这里我首先使用glob()从目录中获取扩展名为*.csv的所有文件。之后,我循环遍历每个文件并使用fopen()fgetcsv()读取它。)

<?php

    $files = glob("$PathToCreate$version/*.csv");

    foreach($files as $file) {

        if (($handle = fopen($file, "r")) !== FALSE) {
            echo "<b>Filename: " . basename($file) . "</b><br><br>";
            while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
                echo implode("\t", $data);
            }
            echo "<br>";
            fclose($handle);
        } else {
            echo "Could not open file: " . $file;
        }

    }

?>

【讨论】:

  • 天哪,太好了,谢谢,有没有办法通过标题来定位特定数据?
  • @Dgeorgex000000 不客气! (有没有办法通过标题来定位特定数据你到底是什么意思?)
  • csv 中的每一行数据都在标题/标题下,是否有一种简单的方法可以仅从某些标题中选择数据,例如仅在第 4 行中的信息或仅在标题 xxx 下的信息
  • @Dgeorgex000000 而不是:echo implode("\t", $data);echo $data[3]; 这是你的意思吗?
  • 那是一场火热的性龙卷风的回答,再完美不过了,非常感谢
【解决方案2】:

第一个问题可能是你必须忽略两个目录条目...,它们有特殊含义,对你没用:

$files = scandir($PathToCreate.$version."/"); //scan the folder
foreach($files as $file) { //for each file in the folder
  if ( ! in_array($file, ['.','..'])) {
    $lines = file($file, FILE_IGNORE_NEW_LINES);
    foreach ($lines as $key => $value) {
      $csv[$key] = str_getcsv($value);
    } 
    print_r($csv)
  }
}

【讨论】:

  • 1.检查每个文件是否既不是. 也不是.. 对于整个循环不是很清楚 2.$csv = fgetcsv(); 什么?
  • @Rizier123 about 2: 抱歉,意外粘贴 :-( 感谢您指出这一点。
  • @Rizier123 关于 1:“不是很清楚”?当然有多种方式可以做到这一点,你使用glob,也很好。但是这种情况“不清楚”是什么?
  • 假设我们有 10k 个文件。如果每个文件既不是. 也不是..,那么检查每个文件不是很聪明,你最好在循环之前用array_diff() 过滤它们,这也有助于提高性能!
  • @Rizier123 我怀疑这是这里的问题:-) OP 提到了上传的文件。他会非常忙于上传 10k 文件 :-) 但从理论上讲你是对的。
猜你喜欢
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 2014-03-17
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多