


Application example of PHP file reading function, _PHP tutorial
Application example of PHP file reading function,
PHP file reading operation involves more PHP file operation functions than file writing operation, which will be detailed in the code example Introduce these functions.
The method of reading data stored in text files mainly involves three steps and some file operation functions as follows:
1. Open a file (file operation function: fopen)
2. File data reading (file operation functions: fgets, file, readfile, feof, etc.)
3. Close the file (file operation function: fclose)
The following still uses an example of PHP file reading and writing operation code to explain the specific application of the file reading method. In the example, by calling different PHP file reading operation functions to read the data in the text file, you can deepen PHP file reading. Get an understanding of operation functions so that they can be reasonably applied in PHP website development. The data written in the text file comes from the file writing tutorial of PHP file reading and writing operations. You can also refer to this article for the file reading and writing mode in the fopen function.
PHP file reading operation code example
<? $readFun = "fread"; switch ($readFun) { case "fgetss": @$fp = fopen("leapsoulcn.txt","r") or die("system error"); $allowable_tags = "<h1>"; while (!feof($fp)) { $output = fgetss($fp,100,$allowable_tags); echo $output; } fclose($fp); break; case "fgetcsv": @$fp = fopen("leapsoulcn.txt","r") or die("system error"); while (!feof($fp)) { $output = fgetcsv($fp,100,"\t"); print_r($output); } fclose($fp); break; case "readfile": echo readfile("leapsoulcn.txt"); break; case "fpassthru": @$fp = fopen("leapsoulcn.txt","r") or die("system error"); if(!fpassthru($fp)) exit(); fclose($fp); break; case "file": $output = file("leapsoulcn.txt"); print_r($output); break; case "fgetc": @$fp = fopen("leapsoulcn.txt","r") or die("system error"); while (!feof($fp)) { $str = fgetc($fp); echo ($str == "\n"?"<br/>":$str); } fclose($fp); break; case "fread": @$fp = fopen("leapsoulcn.txt","r") or die("system error"); echo fread($fp,300); fclose($fp); break; default: @$fp = fopen("leapsoulcn.txt","r") or die("system error"); while (!feof($fp)) { $output = fgets($fp,100); echo $output; } fclose($fp); break; } ?>
Note: In the above example, you can call different PHP file reading methods by assigning a value to $readFun. The PHP file reading operation functions involved are fgets, fgetss, fgetcsv, readfile, fpassthru, file, fgetc functions.
The difference between PHP file reading operation functions fgets, fgetss, and fgetcsv
In the code example, the default PHP file reading operation function is fgets. The functions of fgetss and fgetcsv functions are the same as fgets, and they both read the file one line at a time until the end of the file. Here I set the data length to be read in the text file to 100, that is, the maximum read length is 99 (100-1). In this way, when the newline character n or the end of file character EOF is encountered, or 99 is read from the file Stop reading data when bytes are reached. The fgets function returns the data read from the file, in string type.
The fgetss function is a variant of the fgets function. It can strip PHP and HTML tags and filter unnecessary data by passing the third parameter, which can improve website security. For example, user input data can be filtered in the guestbook. The fgetss function prototype is as follows:
string fgetss(resource fp,int length, string[optional] allowable_tags)
The allowable_tags parameter is optional. In the example, I wrote a line of text containing html, body, and h1 tags in the leapsoulcn.txt file in advance, and then in the code I set that only the h1 tag can appear.
The fgetcsv function is another variant of fgets. The difference is that when the data written in your text file uses delimiters, you can use fgetcsv to break one line into multiple lines, and the returned result is stored in an array. , the function prototype is as follows:
array fgetcsv(resource fp,int length, string[optional] delimiter,string[optional] enclosure)
delimiter is optional. Since I used t in the data written to the file before, in the example, I used t as the delimiter in the file reading function fgetcsv, and then printed out the value returned by fgetcsv through print_r. Array structure.
What the three PHP file reading operation functions fgets, fgetss, and fgetcsv have in common is that they all need to use the fopen function to open the read file in advance, and at the same time use the feof function to determine whether the file pointer reaches the end of the file. Remember to wait until the reading operation is completed. Then use the fclose function to close the file.
fgetc: Read a single character
The fgetc function is used to read a character. In the code example, I read the characters one by one. When n characters are encountered, they are converted into br tags in the html file so that the specific line break effect can be displayed in the browser. Of course The efficiency of this function is definitely relatively low, and its use is not recommended.
The difference between PHP file reading operation functions readfile, fpassthru and file
What the three functions have in common is that they can read the entire file at one time, instead of reading one line or one character at a time. The difference is:
The readfile function opens a file and returns the file content to be output directly on the browser. Like the fopen function, the function return value is the total number of characters in the file. The second parameter of the readfile function is optional and indicates whether PHP should search for the file in include_path. In the code example, I use the echo statement not to output the read file content, but to output the total number of file characters read. The read file content has been automatically output by the readfile function. This must be clear! The readfile function prototype is as follows:
int readfile(string filename,int[optional] use_include_path)
The file function is another way to read a file. It sends the read file content to an array, with one array unit per line. The file function prototype is as follows:
array file(string filename,bool[optional] use_include_path)
The fpassthru() function is used to output all remaining data at the file pointer, that is, if the file pointer is not at the beginning, it only outputs the data after the file pointer. This function reads the given file pointer from the current position to EOF and writes the result to the output buffer. The return value is the number of characters output. When an error occurs, FALSE is returned. Compared with the readfile() function, the fpassthru() function needs to open the file first, and then close the file after the data is read.
fread与file_exists、filesize函数
fread函数也是读取文件的一种方法,其可以从文件中读取任意字节,要么满足length要么读到文件末尾。read函数原型如下:
string fread(resource fp,int length)
在用到fread函数时,当你想读取文件全部数据,又不知道文件数据长度时,filesize函数可以解决这个问题,即
<? @$fp = fopen("leapsoulcn.txt","r") or die("system error"); echo fread($fp,filesize("leapsoulcn.txt")); fclose($fp); ?>
在PHP文件读写操作教程中我们还没有使用过file_exists函数,通常在PHP网站开发中,出于各种考虑,有时当文件不存在时,我们并不像创建新文件,这时我们就需要在使用fopen函数前使用file_exists函数判断文件是否存在,即
<? if(file_exists("leapsoulcn.txt")) { //进行PHP文件读写操作 } ?>
以上为大家介绍了PHP读取文件内容的各种方法,通过合理应用PHP文件读写操作函数,可以实现简单的留言本、网站log记录等功能。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
