Home >Backend Development >PHP Problem >How to read a line of text data in php and convert it into an array
Implementation steps: 1. Use the fopen() function to open the text file, and use the fgets() function to read a line of text data, the syntax is "fgets(fopen("file path", "r"),1024) " will return a row of data of string type; 2. Use the explode() function to convert the read row of data into an array type, with the syntax "explode(' ', read row of data)".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
In php, you can use fgets () and explode() functions to read a line of text data and convert it into an array.
fgets() function is used to read one row of data at a time, and the return value is a string type
explode() function is used Convert a line of data of string type to array type
#Implementation steps:
1. Use the fopen() function to open the text file. And use the fgets() function to read a line of text data
<?php header("Content-type:text/html;charset=utf-8"); $handle = @fopen("./test.txt", "r"); $info = fgets($handle,1024); var_dump($info); ?>
The data read is a string type and contains a newline character.
2. The explode() function converts the read row of data into an array type
<?php header("Content-type:text/html;charset=utf-8"); $handle = @fopen("./test.txt", "r"); $info = fgets($handle,1024); var_dump($info); $arr=explode(' ',$info); var_dump($arr); ?>
Recommended study: "PHP Video Tutorial》
The above is the detailed content of How to read a line of text data in php and convert it into an array. For more information, please follow other related articles on the PHP Chinese website!