Reading *.csv files from directory and showing the content of each file fails

£可爱£侵袭症+ 提交于 2019-12-23 09:15:34

问题


I need help with reading the folder and opening / outputting the csv data, I have used examples other people have written but none of them have worked for me.

What I currently have is this, but it doesn't output the files:

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

}

回答1:


This should work for you:

(Here I first grab all files out of the directory which have the extension *.csv with glob(). After this I loop through each file and read it with fopen() and 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;
        }

    }

?>



回答2:


The first issue probably is that you have to ignore the two directory entries . and .. which have special meaning and are not useful for you:

$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)
  }
}


来源:https://stackoverflow.com/questions/29608709/reading-csv-files-from-directory-and-showing-the-content-of-each-file-fails

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