站长资讯网
最全最丰富的资讯网站

php中txt怎么转成数组

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

php中txt怎么转成数组

本教程操作环境: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("rn", $content); //转换成数组         $array = array_filter($array);  // 去空         $array = array_unique($array);  // 去重         print_r(json_encode($array));     } }else{     echo "文件不存在"; }

执行结果:

php中txt怎么转成数组

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

赞(0)
分享到: 更多 (0)