php中txt轉成陣列的方法:1.利用「file_get_contents(txt檔案物件)」語句將檔案內容讀入字串;2、利用explode()函數將讀入的字串轉換為陣列即可,語法為「explode("\r\n",字串物件)」。

本教學操作環境:windows10系統、PHP7.1版、DELL G3電腦
php中txt怎麼轉換成陣列
file_get_contents() 把整個檔案讀入一個字串中。
該函數是用來把檔案的內容讀入到一個字串中的首選方法。如果伺服器作業系統支持,也會使用記憶體映射技術來增強效能。
語法
1 | file_get_contents (path,include_path,context,start,max_length)
|
登入後複製
explode() 函數使用字串分割另一個字串,並傳回由字串組成的陣列。
語法
1 | explode (separator,string,limit)
|
登入後複製
範例如下:
文字內容範例:
1 2 3 4 5 6 7 | 我爱你
中国
我爱你
NO.1
TOP1
123456789
123456
|
登入後複製
程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$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');
$array = explode ( "\r\n" , $content );
$array = array_filter ( $array );
$array = array_unique ( $array );
print_r(json_encode( $array ));
}
} else {
echo "文件不存在" ;
}
|
登入後複製
執行結果:

推薦學習:《PHP影片教學》
以上是php中txt怎麼轉成數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!