Home  >  Article  >  Backend Development  >  How to convert text file to array class in php

How to convert text file to array class in php

青灯夜游
青灯夜游Original
2021-10-29 19:15:373566browse

In PHP, you can use the file() function to convert a text file into an array class. This function can store the contents of the entire file into an array line by line (including newlines); the syntax "file( $filename,$flags,$context)".

How to convert text file to array class in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, you can use the file() function To convert text file to array class.

PHP file() can read the entire file into an array. This function will store the contents of the file into the array line by line (including newlines). This array is returned on success, FALSE on failure.

Syntax:

file($filename,$flags,$context)

Parameter description is as follows:

  • $filename: the name or path of the file to be read;
  • $ flags: Optional parameter, flags can be one or more of the following constants:
    • FILE_USE_INCLUDE_PATH: Find files in include_path;
    • FILE_IGNORE_NEW_LINES: Do not add a newline character at the end of each element of the array;
    • FILE_SKIP_EMPTY_LINES: Skip empty lines.
  • $context: Context resource created using the stream_context_create() function.

Example: Read the following file

How to convert text file to array class in php

<?php
header("Content-Type: text/html;charset=utf-8");    //设置字符编码
$file = &#39;test.txt&#39;;
$filearr = file($file,FILE_IGNORE_NEW_LINES);
var_dump($filearr);
?>

Output result:

How to convert text file to array class in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert text file to array class 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