简体   繁体   中英

How do I read the content (lines) of the file in my $file?

<?php

$dir = 'data';

// Check if the directory exists
if (file_exists($dir) && is_dir($dir))
{

    // Get the files of the directory as an array
    $scan_arr = scandir($dir);
    $files_arr = array_diff($scan_arr, array(
        '.',
        '..'
    ));

    foreach ($files_arr as $file)
    {
        // Open file and read
        $f = fopen($file, 'r');
        // TRYING TO READ FIRST LINE OF $FILES IN THE ARRAY **<-------------HERE**
        $handle = fgets($f, 1024);

        //Get the file path
        $file_path = "data" . $file;

        // Get the file extension
        $file_ext = pathinfo($file_path, PATHINFO_EXTENSION);
        if ($file_ext == "txt")
        {
            echo "File name: " . $file . "<br/>";
        }
        else
        {
            echo "The file " . $file . " is not a txt";
        }

    }

}
else
{
    echo "Directory does not exists";
};
?>

//Here is the result:

Warning: fopen(myFile.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\tma\test.php on line 13

Warning: fgets() expects parameter 1 to be resource, bool given in C:\xampp\htdocs\tma\test.php on line 15
File name: myFile.txt

Warning: fopen(p1IH.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\tma\test.php on line 13

Warning: fgets() expects parameter 1 to be resource, bool given in C:\xampp\htdocs\tma\test.php on line 15
File name: p1IH.txt

Warning: fopen(ppGM.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\tma\test.php on line 13

Warning: fgets() expects parameter 1 to be resource, bool given in C:\xampp\htdocs\tma\test.php on line 15
File name: ppGM.txt

Warning: fopen(shit.xml): failed to open stream: No such file or directory in C:\xampp\htdocs\tma\test.php on line 13

Warning: fgets() expects parameter 1 to be resource, bool given in C:\xampp\htdocs\tma\test.php on line 15
The file shit.xml is not a txt
$f = fopen($dir . "/" . $file, 'r');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM