php中txt怎么转成数组

php中txt怎么转成数组,第1张

php中txt怎么转成数组

php中txt转成数组的方法:1、利用“file_get_contents(txt文件对象)”语句将文件内容读入字符串;2、利用explode()函数将读入的字符串转化为数组即可,语法为“explode("\r\n",字符串对象)”。

本教程 *** 作环境:windows10系统、PHP7.1版、DELL G3电脑

php中txt怎么转成数组

file_get_contents() 把整个文件读入一个字符串中。

该函数是用于把文件的内容读入到一个字符串中的首选方法。如果服务器 *** 作系统支持,还会使用内存映射技术来增强性能。

语法

file_get_contents(path,include_path,context,start,max_length)

explode() 函数使用一个字符串分割另一个字符串,并返回由字符串组成的数组。

语法

explode(separator,string,limit)

示例如下:

文本内容示例:

我爱你
中国
我爱你
NO.1
TOP1
123456789
123456

代码:

/**
 *  读取txt文件内容转换成数组
 */
$file = 'data.txt';
if(file_exists($file)) {
    $content = file_get_contents($file);    //文件内容读入字符串
    if (empty($content)) {
        echo "文件内容为空";
    } else {
        $content = mb_convert_encoding($content, 'UTF-8', 'ASCII,UTF-8,GB2312,GBK,BIG5'); //转换字符编码为utf-8
        $array = explode("\r\n", $content); //转换成数组
        $array = array_filter($array);  // 去空
        $array = array_unique($array);  // 去重
        print_r(json_encode($array));
    }
}else{
    echo "文件不存在";
}

执行结果:

推荐学习:《PHP视频教程》

以上就是php中txt怎么转成数组的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/680499.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存