因此,我需要首先打开一个目录,我做到了,它也能工作,然后我需要使名为"."answers".."的文件不显示,我做到做到了,而且它也能正常工作,但在所有这些之后,我需要打开该目录中的每个文件(除了".."answers".")并显示它的内容。
我的代码在这里:
<?php
$handle = opendir('data');
$files = array();
while (false !== ($file = readdir($handle))) {
if ($file!=="." && $file!=="..") {
$files = $file;
print_r ('<p>' . ucfirst($files) .'</p>');
}
foreach($files as $dataz) {
$handle2 = fopen('data/'.$dataz, 'r');
while (!feof($handle2)) {
$name = fgets($handle2);
echo '<p>' . $name .'</p>';
}
fclose($handle2);
}
}
closedir($handle);
?>
我得到的错误是:警告:在第30行的/home/something/something/websitephp/wweather.php中为foreach()提供的参数无效调用堆栈:0.0025 325952 1。{main}()/home/something/something/websitephp/wweather.php:0
我认为错误将是$dataz,但我需要它来向fopen指示应该打开哪些文件。
此处
$files = $file;
每次都会重写数组
使用
$files[] = $file;
而是
编辑
$handle = opendir('data');
$files = array();
while (false !== ($file = readdir($handle))) {
if ($file !== "." && $file !== "..") {
$files[] = $file;
print_r('<p>' . ucfirst($files) . '</p>');
}
}
foreach ($files as $dataz) {
$handle2 = fopen('data/' . $dataz, 'r');
while (!feof($handle2)) {
$name = fgets($handle2);
echo '<p>' . $name . '</p>';
}
fclose($handle2);
}
closedir($handle);
我重新组织了代码并使其在中工作
$directoryPath = 'data';
// Get the file listing
$files = array();
foreach (scandir($directoryPath) as $file) {
if (is_file("$directoryPath/$file")) {
$files[] = $file;
}
}
// Display each files content
foreach($files as $file) {
echo '<p>' . ucfirst($file) .'</p>';
$contents = file_get_contents("$directoryPath/$file");
// Print each line of the file
foreach (explode("'n", $contents) as $line) {
echo '<p>' . $line .'</p>';
}
}
所以,我目前的解决方案是:
<?php
$handle = opendir('data');
$files = array();
while (false !== ($file = readdir($handle))) {
if ($file!=="." && $file!=="..") {
$files[] = $file;
print_r ('<p>' . strtoupper($file) .'</p>');
}
foreach($files as $dataz) {
$handle1 = fopen('data/'.$dataz, 'r');
while (!feof($handle1)) {
$name = fgets($handle1);
echo '<p>' . $name .'</p>';
}
fclose($handle1);
}
}
closedir($handle);
?>
它获取除"."answers".."之外的文件名,并读取文件的内容,但当它显示第二个文件的内容时,首先显示第一个文件的属性,在显示第二文件的属性后,即应显示。出于某种原因,$name似乎保留了前一个文件的内容
要理解我的意思,请看一下这个链接。