Home  >  Article  >  Backend Development  >  How to convert txt to array in php

How to convert txt to array in php

WBOY
WBOYOriginal
2022-02-10 16:35:182998browse

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)".

How to convert txt to array in php

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:

How to convert txt to array in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn