How to convert txt text into string array in php
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics









