php - 从目录中读取 *.csv 文件并显示每个文件的内容失败

标签 php csv fgetcsv opencsv scandir

我在读取文件夹和打开/输出 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)

}

最佳答案

这应该适合你:

(在这里,我首先从扩展名为 *.csvglob() 的目录中抓取所有文件。之后我遍历每个文件并使用 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;
        }

    }

?>

关于php - 从目录中读取 *.csv 文件并显示每个文件的内容失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29608709/

相关文章:

PHP - fgetcsv() 重置指针

php - Yii - 如何上传 csv 以保存在数据库中?

c - 使用 C 和动态分配从 CSV 读取和保存值

php - 如何让 PHP 的 fgetcsv() 识别 Classic Mac (CR) 换行符?

php - 我一直收到 "You have an error in your SQL syntax",如果直接运行,SQL 会工作

php - 包括 COUNT() = 0 的结果

java - 为什么 CSVWriter 和 CSVReader 使用不同的默认转义字符?

python - 如何将for循环中的结果写入多个CSV文件

php - 在哪里可以找到 facebook php 类引用?

php - mysql show table/columns - 性能问题