从目录中读取 *.csv 文件并显示每个文件的内容失败
Reading *.csv files from directory and showing the content of each file fails
我在读取文件夹和打开/输出 csv 数据方面需要帮助,我使用了其他人编写的示例,但 none 对我有用。
我现在有的是这个,但是没有输出文件:
$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
和 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;
}
}
?>
第一个问题可能是您必须忽略两个目录条目 .
和 ..
,它们具有特殊含义并且对您没有用:
$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)
}
}
我在读取文件夹和打开/输出 csv 数据方面需要帮助,我使用了其他人编写的示例,但 none 对我有用。
我现在有的是这个,但是没有输出文件:
$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
和 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;
}
}
?>
第一个问题可能是您必须忽略两个目录条目 .
和 ..
,它们具有特殊含义并且对您没有用:
$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)
}
}