Home > Article > Backend Development > PHP file processing—reading files (one character, string)
PHP file processing - reading file (one character, string)
Reading a file can not only read the entire file, nor just Read a line of data, you can also read a character, you can read a string of specified length!
In the previous article "PHP File Processing - How to read a file (one line, the entire file)", we introduced the detailed explanation of how to read one line of the file and the entire file, so in this article We will continue to introduce two fgetc() functions and fread() functions for you!
1: Read a character: fgetc() function
When searching and replacing a certain character in a file, you need to To read a certain character permanently, you can use the fgetc() function in PHP to achieve this function. The syntax format of the function is as follows;
string fgetc ( resource $handle )
The function returns a character, which is obtained from the file pointed to by handle. If EOF is encountered, false will be returned.
In the following example, the fgetc() function is used to read the contents of the file character by character and output. The specific example code is as follows:
<?php header("Content-Type:text/html; charset=utf-8"); $fopen = fopen("tm.txt","rb"); //创建文件资源 while (false!==($chr =fgetc($fopen))){ //使用fgetc()函数取得一个字符,判断是否为false echo $chr; //如果不是输出该字符 } fclose($fopen); //关闭资源 ?>
The output result is:
2: Read a string of specified length: fread() function
fread() can flush files Read data of a specified length in the function syntax format is as follows:
string fread ( resource $handle , int $length )
The parameter handle is the file to be read, and the parameter length is the specified number of bytes to be read. Execution stops when the function reads length bytes or reaches EOF.
The following is to use the fread() function to read the contents of the file. The specific example code is as follows:
<?php header("Content-Type:text/html; charset=utf-8"); $filename = "tm.txt"; //要读取的文件 $fp = fopen($filename,"rb");//打开文件 echo fread($fp,32); //使用 fread()函数读取文件内容的前32个字节 echo "<p>"; echo fread($fp,filesize($filename)); //输出其余的文件内容 ?>
The output result is as follows:
This chapter ends here. In the next article, we will introduce to you how PHP writes data to files and operates files. For details, please read "PHP File Processing—Writing Files and Operating Files"!
The above is the detailed content of PHP file processing—reading files (one character, string). For more information, please follow other related articles on the PHP Chinese website!