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

本教程操作环境:windows10系统、PHP7.1版、DELL G3电脑
file_get_contents() 把整个文件读入一个字符串中。
该函数是用于把文件的内容读入到一个字符串中的首选方法。如果服务器操作系统支持,还会使用内存映射技术来增强性能。
语法
立即学习“PHP免费学习笔记(深入)”;
file_get_contents(path,include_path,context,start,max_length)
explode() 函数使用一个字符串分割另一个字符串,并返回由字符串组成的数组。
语法
立即学习“PHP免费学习笔记(深入)”;
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怎么转成数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号