PHP从文件错误中读取内容

时间:2014-11-01 12:59:56

标签: php file directory fgets

所以我需要首先打开一个目录,在我需要制作名为“。”的文件之后,我这样做了。和“..”不显示,我做了,它也工作,但在所有这一切之后,我需要打开该目录中的每个文件(除了“。”和“..”)并显示它的内容。

我的代码在这里:

<?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/weather.php中的foreach()提供的参数无效。调用堆栈:0.0025 325952 1. {main}()/ home / something / something / websitephp / weather.php: 0

我认为错误将是$ dataz,但我需要这样才能向fopen表明应该打开哪些文件。

3 个答案:

答案 0 :(得分:1)

这里

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

答案 1 :(得分:0)

我重新整理了代码并使其正常工作

$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>';            
    }
}

答案 2 :(得分:-1)

所以,我现在的解决方案是:

<?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);
?>

它获取的文件名除了&#34;。&#34;和&#34; ..&#34;并且在读取文件的内容时,但是当它显示第二文件的内容时,首先显示第一文件的内容,并且在显示第二文件的内容之后,应该显示该内容。出于某种原因,$ name似乎保留了上一个文件的内容。

要说明我的意思,请查看此link