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

How to convert txt text into string array in php

PHPz
PHPzOriginal
2023-04-18 15:21:561019browse

In PHP, there are many ways to convert txt text files into string arrays. Two simple methods will be introduced below.

Method 1: Use the file() function

The file() function is a simple function provided by PHP. It can directly read the text file and convert the file content into an array, with each line of text Corresponds to an element in the array.

The sample code is as follows:

<?php
$file = "data.txt"; // txt文件的路径
$array = file($file); // 以行为单位读取整个文件
print_r($array); // 输出数组内容
?>

Use the above code to read the contents of the data.txt file and output it in the form of an array. If the text file contains multiple lines of text, the array will contain an equal number of elements.

Method 2: Use the fopen() and fgets() functions

The fopen() function can open a file and read the file contents. The fgets() function can read the contents of a text file line by line and return each line as a string.

The sample code is as follows:

<?php
$file = "data.txt";
$array = array(); // 定义空数组,用于保存文件内容
if(($fp = fopen($file, "r")) !== FALSE){ // 打开文件
    while(!feof($fp)){ // 是否到达文件末尾
        $line = fgets($fp); // 读取一行文件内容
        $array[] = $line; // 将行字符串存放到数组中
    }
    fclose($fp); // 关闭文件
}
print_r($array); // 输出数组内容
?>

Using the above code, first open the data.txt text file through the fopen() function. Then read the file content line by line through the loop and the fgets() function, and save each line into an array until the end of the file. Finally, print out an array containing the contents of the file.

Summary:

In any case, converting a txt text file to a string array is very simple in PHP. You can choose the method that suits you based on actual needs and practice it in your project.

The above is the detailed content of How to convert txt text into string 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