How to convert txt into an array in php: 1. Use the "file_get_contents (txt file object)" statement to read the file contents into a string; 2. Use the explode() function to convert the read string into Just use an array, and the syntax is "explode("\r\n", string object)".
The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer
How to convert txt into an array in php
file_get_contents() Read the entire file into a string.
This function is the preferred method for reading the contents of a file into a string. If supported by the server operating system, memory mapping technology is also used to enhance performance.
Syntax
file_get_contents(path,include_path,context,start,max_length)
explode() function uses one string to split another string and returns an array composed of strings.
Syntax
explode(separator,string,limit)
The example is as follows:
Text content example:
我爱你 中国 我爱你 NO.1 TOP1 123456789 123456
Code:
/** * 读取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 "文件不存在"; }
Execution result:
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to convert txt to array in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
