php随机读取当前txt文件内容

文章描述:

php如何获取当前文件夹下面所有txt文件,然后随机读取三个文件的内容

 

文件路径

header('Access-Control-Allow-Origin:*');
//取得当前文件所在目录
$dir  =  dirname(__FILE__);
//判断目标目录是否是文件夹
$file_arr = array();
if(is_dir($dir)){
    //打开
    if($dh = @opendir($dir)){
        //读取

        while(($file = readdir($dh)) !== false){

            if($file != '.' && $file != '..'){

                $file_arr[] = $file;
            }

        }
        //关闭
        closedir($dh);
    }
}

获取所有txt文件

$file_str = array();
foreach ($file_arr as $key=>$val){
    if(substr($val,-4)=='.txt'){
        $file_str[] = $val;
    }
}

结果

Array
(
    [0] => hello.txt
    [1] => news.txt
    [2] => product.txt
    [3] => welcome.txt
)

 随机获取三个文件

$str_rand = array_rand($file_str,3);
$files = array();
foreach ($file_str as $k=>$v){
    if(in_array($k, $str_rand)){
        $files[] = $v;
    }
}

结果

Array
(
    [0] => hello.txt
    [1] => news.txt
    [2] => product.txt
)

 读取文件内容

$result = [];
foreach ($files as $k => $v) {
    $number = $k + 1;
    $key = $number;
    $f = fopen($v, 'r');
    $content = fread($f, filesize($v));
    fclose($f);
    $result[$key] = $content;
}

结果

Array
(
    [1] => 你好!
    [2] => 新闻
    [3] => 产品
)

数组转字符串

$datastr = implode(",", $result);
echo $datastr;

 

发布时间:2021/06/18

发表评论