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.1top1123456789123456
代码:
/** * 读取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怎么转成数组的详细内容。