Home  >  Article  >  Backend Development  >  How to read a line of text data in php and convert it into an array

How to read a line of text data in php and convert it into an array

青灯夜游
青灯夜游Original
2022-06-28 17:35:342261browse

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

How to read a line of text data in php and convert it into an array

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);
?>

How to read a line of text data in php and convert it into an array

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(&#39; &#39;,$info);
var_dump($arr);
?>

How to read a line of text data in php and convert it into an array

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!

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