PHP遍历文件夹下的文件

这篇博客主要介绍了如何在PHP中处理中文编码问题,确保在有中文的文件夹下不会出现乱码。通过自动识别编码并转换为UTF-8,可以避免因GBK编码导致的乱码现象。此外,还讲述了如何使用PHP遍历文件夹下的所有文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录中有中文时将中文编码自动转换为UTF-8

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<?php
function my_dir($dir) {
    $files = [];
    if(@$handle = opendir($dir)) {
        while(($file = readdir($handle)) !== false) {
            if($file != ".." && $file != ".") {
                // if(is_dir($dir . "/" . $file)) { //如果是子文件夹,进行递归
                //     $files[$file] = my_dir($dir . "/" . $file);
                // } else {
                    $files[] = characet($file);
                // }
            }
        }
        closedir($handle);
    }
    return $files;
}
function characet($data){
  if( !empty($data) ){
    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
    if( $fileType != 'UTF-8'){
      $data = mb_convert_encoding($data ,'utf-8' , $fileType);
    }
  }
  return $data;
}
// echo "<pre>";
// print_r(my_dir("./"));
// echo "</pre>";
$array = my_dir("./");
// var_dump($array);
foreach ($array as $value)
{
    echo "<a href='$value'><h2>$value</h2></a>";
}
?>
</html>

PHP识别中文编码并自动转换为UTF-8

php自动识别编码,若里面有中文的话,将其转换为UTF-8就最好了,因为中文在Gbk编辑情况情况下,有可能会乱码,这个和客户端和服务端编码都有关系,为了避免乱码,我们可以使用下面的函数将其自动转换为UTF8国际标准编码:

<?php
function characet($data){
  if( !empty($data) ){
    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
    if( $fileType != 'UTF-8'){
      $data = mb_convert_encoding($data ,'utf-8' , $fileType);
    }
  }
  return $data;
}
?>

PHP遍历文件夹下的所有文件

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<?php
function my_dir($dir) {
    $files = [];
    if(@$handle = opendir($dir)) {
        while(($file = readdir($handle)) !== false) {
            if($file != ".." && $file != ".") {
                if(is_dir($dir . "/" . $file)) { //如果是子文件夹,进行递归
                    $files[$file] = my_dir($dir . "/" . $file);
                } else {
                    $files[] = characet($file);
                }
            }
        }
        closedir($handle);
    }
    return $files;
}
function characet($data){
  if( !empty($data) ){
    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
    if( $fileType != 'UTF-8'){
      $data = mb_convert_encoding($data ,'utf-8' , $fileType);
    }
  }
  return $data;
}
// echo "<pre>";
// print_r(my_dir("./"));
// echo "</pre>";
$array = my_dir("./");
var_dump($array);
// foreach ($array as $value)
// {
//     echo "<a href='$value'><h2>$value</h2></a>";
// }
?>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值