Home  >  Article  >  Backend Development  >  PHP code to read the contents of a txt file and assign it to an array_PHP tutorial

PHP code to read the contents of a txt file and assign it to an array_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:23:57841browse

The content of the 2010-12-15.txt file is as follows:

Copy code The code is as follows:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
T01
T02
T03
T04
T05
T06
T07
T08
T09
T10
T11
T12
T13
T14
T15
T16

The idea is as follows: use file_get_contents() to obtain the contents of the txt file, and then convert the obtained string into an array through explode(). To get the length of an array, use the count() function.

PHP Code
Copy code The code is as follows:

$file = '2010-12-15. txt';
$content = file_get_contents($file);
//echo $content;

$array = explode("\r\n", $content);
/ /print_r($array);

for($i=0; $i〈count($array); $i++)
{
echo $array[$i].'〈br /〉';
}

About the line breaks in txt documents
In regular expressions, there is a \n that means newline, and another \r that means carriage return (This is what led to the idiot Chinese translation of "Enter"). When processing String or console output, no matter which one you bring, you can wrap the line.

But in txt, none of them are standard line breaks. Only the combined \r\n is a line break (this is true for the default line breaks in the entire Windows).

means\rPress Enter to indicate that the line is over, the cursor will go back to the beginning, and then\nmove down one line to create a new line.

Because of this, when I used scanner() to search txt documents with regular expressions, I was at a loss and couldn't find the problem at all.

About file_get_contents()
The file_get_contents() function reads the entire file into a string.

The file_get_contents() function is the preferred method for reading the contents of a file into a string. If supported by the operating system, memory mapping technology is also used to enhance performance.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324445.htmlTechArticle2010-12-15.txt file content is as follows: Copy the code code as follows: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 T01 T02 T03 T04 T05 T06 T07 T08 T09 T10 T11...
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