微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP:使用 glob 函数时无法显示文本文件的内容

如何解决PHP:使用 glob 函数时无法显示文本文件的内容

对于照片日记,我有一个 PHP 文件,可以自动文件夹中提取图像和视频。现在我也希望它自动显示 txt 文件内容,但我无法让它工作。

这是适用于图像和视频的代码

$files = glob("images/*.*");
rsort($files);
for ($i = 0;$i < count($files);$i++) {
    $image = $files[$i];
    $supported_file = array(
        'jpg','jpeg','png','mp4',);
    $ext = strtolower(pathinfo($image,PATHINFO_EXTENSION));
    if (in_array($ext,$supported_file)) {
        
        if ($ext == 'mp4') {
            echo '<video width="900" controls loop> <source src="' . $image . '" type="video/mp4"/>'; 
            echo '</video>'."<br /> <br />";
        }

        else {
            echo '<img src="' . $image . '" width="900" />'."<br /> <br />";
        }
        
    } else {
        continue;
    }
    }

我尝试将“txt”添加到supported_file列表,然后在第二个“if”之后添加代码

    else ($ext == 'txt') {
        echo readfile( "' . $image . '");   
}

但它打破了页面。我已经搜索过有关显示文本文件内容的帮助,但没有看到有关在使用 glob 函数时如何执行此操作的任何信息。

有什么想法吗?

解决方法

我想通了(在一些外部帮助下)!

有效的文本文件命令是:

 elseif ($ext === 'txt') {
        echo '<pre>' . file_get_contents($image) . '</pre>' . "<br />";
    }

据我所知,“pre”有两件事:1) 允许在“获得”内容后在页面上显示原始文本文件的格式(分段符和 html 标记);和 2) 充当 css 样式的标记,这有助于使文本在页面上随心所欲。

整个脚本还有一些其他的变化,所以我会把它全部贴在这里,以防有人好奇或有任何意见。

<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

$files = glob("images/*.*");
rsort($files);
for ($i = 0;$i < count($files);$i++) {
   $image = $files[$i];
   $supported_file = array(
    'jpg','jpeg','png','mp4','txt',);
$ext = strtolower(pathinfo($image,PATHINFO_EXTENSION));
# echo "<pre>". $image . "</pre>";
if (in_array($ext,$supported_file)) {
    
    if ($ext == 'mp4') {
        echo '<video width="900" controls loop> <source src="' . $image . '" type="video/mp4"/>'; 
        echo '</video>'."<br /> <br />";
    }

  elseif ($ext === 'txt') {
        echo '<pre>' . file_get_contents($image) . '</pre>' . "<br />";
    }

    else {
        echo '<img src="' . $image . '" width="900" />'."<br /> <br />";
    }
    
} else {
    continue;
}
}
?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。