为什么
fgets
和fopen
无法“打开流”(除了输入文件的最后一行)?
我正在尝试读取目录树和txt文件的文件并打开每个文件。
filelist.txt
包含:
a/1600/file.txt
b/1600/file.txt
c/1600/file.txt
目录:
c/1600/file.txt 包含文本
directory c
index.php 中的输出是这样的:
警告:file_get_contents(a/1600/file.txt):无法打开流: 第 9 行 /Users/joe/Sites/php/index.php 中没有此类文件或目录
警告:file_get_contents(b/1600/file.txt):无法打开流: 第 9 行 /Users/joe/Sites/php/index.php 中没有此类文件或目录
目录c
为什么只输出c/1600/file.txt的内容?
index.php(PHP 8.2):
$handle = fopen("filelist.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$eachfilecontents = file_get_contents($line, true);
echo $eachfilecontents;
}
fclose($handle);
}
我已修改您的代码以检查文件,然后再继续下一步
<?php
$handle = fopen("filelist.txt", "r");
if($handle){
while(($line = fgets($handle)) !== false) {
$line = trim($line);
if(file_exists($line)){
$eachfilecontents = file_get_contents($line);
echo $eachfilecontents;
}
else{ echo "File not found: " . $line . "<br>"; }
}
fclose($handle);
}
?>
用此替换您的 index.php 文件代码,它将返回所有文件中的数据。