Home > Backend Development > PHP Problem > How to convert txt to array in php

How to convert txt to array in php

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-15 09:02:01
Original
3078 people have browsed it

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)
Copy after login

explode() function uses one string to split another string and returns an array composed of strings.

Syntax

explode(separator,string,limit)
Copy after login

The example is as follows:

Text content example:

我爱你
中国
我爱你
NO.1
TOP1
123456789
123456
Copy after login

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 "文件不存在";
}
Copy after login

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!

Related labels:
php
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template