This article mainly introduces the application examples of PHP file reading function and the usage and differences of commonly used file data reading functions. It is very detailed. Friends in need can refer to it.
PHP file reading operations involve more PHP file operation functions than file writing operations. These functions will be introduced in detail in the code examples.
The method of reading data stored in text files mainly involves three steps and some file operation functions as follows:
1. Open the file (file operation function: fopen)
2. File data reading (file operation function: fgets, file, readfile, feof, etc.)
3. Close the file (file operation function: fclose)
The following still uses PHP file read and write operation code examples to explain files. The specific application of the reading method. In the example, by calling different PHP file reading operation functions to read the data in the text file, you can deepen your understanding of the PHP file reading 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 involved The fetch operation functions include fgets, fgetss, fgetcsv, readfile, fpassthru, file, fgetc and other functions.
The difference between the PHP file reading operation functions fgets, fgetss, and fgetcsv
In the code example, the default PHP file reading operation function is fgets, fgetss and The function of fgetcsv function is the same as that of fgets, which reads one line from the file at a time until the end of the file. Here I set the data length in the text file to be read 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 the reading from the file is completed, Stop reading data when 99 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. It can improve website security. For example, the guestbook can filter users' Input data, the fgetss function prototype is as follows:
string fgetss(resource fp,int length, string[optional] allowable_tags)
allowable_tags parameter is optional, in the example I 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 decompose one line into multiple lines, and the returned result is stored In the array, the function prototype is as follows:
array fgetcsv(resource fp,int length, string[optional] delimiter,string[optional] enclosure)
delimiter is available option, since I used \t in the data written to the file before, so in the example I used \t as the delimiter in the file reading function fgetcsv, and then printed out the array structure returned by fgetcsv through print_r.
The three PHP file reading operation functions fgets, fgetss, and fgetcsv have in common 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 read After the fetch operation is completed, 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, and when the \n character is encountered, it is converted into an html file. The br tag is used to display specific line wrapping effects in the browser. Of course, the efficiency of this function is definitely relatively low and 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, not at once Read a line or character. The difference is:
The readfile function opens the file, returns the file content and outputs it 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, indicating whether PHP should Find files 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 prototype of the readfile function is as follows:
int readfile(string filename,int[optional] use_include_path)
The file function is another method of reading files. It sends the read file contents to an array. , one array cell per row. The file function prototype is as follows:
array file(string filename,bool[optional] use_include_path)
fpassthru()函数用来输出文件指针处的所有剩余数据,即如果文件指针并不在开头,它只输出文件指针后面的数据。该函数将给定的文件指针从当前的位置读取到EOF,并把结果写到输出缓冲区,返回值为输出的字符数。发生错误时,返回FALSE。与readfile()函数相比,fpassthru()函数需要首先打开文件,数据读取完毕后要关闭文件。
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文件读写操作 } ?>
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。
相关推荐:
The above is the detailed content of Application of PHP file operation functions. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.