php中txt轉(zhuǎn)成數(shù)組的方法:1、利用“file_get_contents(txt文件對(duì)象)”語(yǔ)句將文件內(nèi)容讀入字符串;2、利用explode()函數(shù)將讀入的字符串轉(zhuǎn)化為數(shù)組即可,語(yǔ)法為“explode("rn",字符串對(duì)象)”。
本教程操作環(huán)境:windows10系統(tǒng)、PHP7.1版、DELL G3電腦
php中txt怎么轉(zhuǎn)成數(shù)組
file_get_contents() 把整個(gè)文件讀入一個(gè)字符串中。
該函數(shù)是用于把文件的內(nèi)容讀入到一個(gè)字符串中的首選方法。如果服務(wù)器操作系統(tǒng)支持,還會(huì)使用內(nèi)存映射技術(shù)來(lái)增強(qiáng)性能。
語(yǔ)法
file_get_contents(path,include_path,context,start,max_length)
explode() 函數(shù)使用一個(gè)字符串分割另一個(gè)字符串,并返回由字符串組成的數(shù)組。
語(yǔ)法
explode(separator,string,limit)
示例如下:
文本內(nèi)容示例:
我愛(ài)你 中國(guó) 我愛(ài)你 NO.1 TOP1 123456789 123456
代碼:
/** * 讀取txt文件內(nèi)容轉(zhuǎn)換成數(shù)組 */ $file = 'data.txt'; if(file_exists($file)) { $content = file_get_contents($file); //文件內(nèi)容讀入字符串 if (empty($content)) { echo "文件內(nèi)容為空"; } else { $content = mb_convert_encoding($content, 'UTF-8', 'ASCII,UTF-8,GB2312,GBK,BIG5'); //轉(zhuǎn)換字符編碼為utf-8 $array = explode("rn", $content); //轉(zhuǎn)換成數(shù)組 $array = array_filter($array); // 去空 $array = array_unique($array); // 去重 print_r(json_encode($array)); } }else{ echo "文件不存在"; }
執(zhí)行結(jié)果:
推薦學(xué)習(xí):《PHP視頻教程》