Summary of functions related to PHP file read/write operations

Source: Internet
Author: User
This article mainly introduces the summary of functions related to PHP file read/write operations. This article summarizes fwrite (), fread (), fgets (), fgetc (), file (), readfile () for more information about functions and examples, see I. fwrite () write to file

It is easier to save the data in the program to a file. you can use the fwrite () function to write the string content into the file. In the file, the character sequence \ n is used to represent the line break, indicating the end of a row in the file. Remember this when you need to input or output a line of information at a time. Different operating systems have different end symbols. UNIX-based systems use "" as the end character of the line, and Windows-based systems use "\ n" as the end character of the line, the Macintosh-based system uses "" as the row end character. To write a text file and insert a new row, you must use the line termination symbol of the corresponding operating system. The fwrite () function is prototype as follows:

The code is as follows:


Int fwrite (resource handle, string [, int length]) // write a file


The first parameter must provide the file resource opened by the fopen () function. this function outputs the string content provided by the second parameter to the resource specified by the first parameter. If the third optional parameter lenth is provided, fwrite () will stop when length characters are written. Otherwise, the data is written until the end of the content is reached. If the written content is less than length bytes, the function will also stop after writing all the content. After the fwrite () function is executed, the number of written characters is returned. If an error occurs, FALSE is returned. The following code is an example of writing a file.

The code is as follows:


<? Php
// Declare a variable to save the file name
$ FileName = "data.txt ";
// Use the fopen () function to open the file in write-only mode. if the file does not exist, create it. if the file fails to be opened, use the program
$ Handle = fopen ($ fileName, 'w') or die ('Open'. $ FileName .'
File failed !! ');
// Write 10 rows of data to the file 10 times in a loop
For ($ row = 0; $ row <10; $ row ++ ){
Fwrite ($ handle, $ row. ": www.lampbrother.net \ n ");
}
Fclose ($ handle );
?>

After the program is executed, if a data.txt file exists under the current directory, the file is cleared and 10 rows of data are written. If the data.txt file does not exist, the file is created and 10 rows of data are written. In addition, you can use the fputs () function to write files. This function is an alias for the fwrite () function. if you need to quickly write files, you can use the file_put_contents () function, this is the same as calling the fopen (), fwrite (), and fclose () functions in turn. The code for using this function is as follows:

The code is as follows:


<? Php
// Declare a variable to save the file name
$ FileName = "data.txt ";
// Declare a variable to save the data in the written file
$ Data = "10 rows of data in total ";
For ($ row = 0; $ row <10; $ row ++ ){
// Store 10 data in a string variable
$ Data. = $ row. ": www.lampbrother.net \ n ";
}
// Write all data to the specified file at a time
File_put_contents ($ fileName, $ data );
?>

This function can directly write data to a specified file. If you call the function multiple times at the same time and write data to the same file, the file only saves the data written by the last call to this function. Because the file will be re-opened and the original data in the file will be cleared at the time of every drop, so it is not allowed to write multiple rows of data consecutively as the first program.

II. reading file content

In PHP, multiple standard functions are provided to read content from files. you can select which function to use in the program based on their features. The functions and descriptions of these functions are shown in the following table.

When reading a File, you should not only pay attention to the line ending symbol "", but also need a standard method for the program to identify when the File ends. this standard is usually EOF (End Of File) character. EOF is a very important concept. almost every mainstream programming language provides corresponding built-in functions to analyze whether it has reached the file EOF. In PHP, use the feof () function. This function accepts an open file resource and determines whether a file pointer is at the end of the file. if it is at the end of the file, TRUE is returned.

① Function fread ()

This function is used to read strings of the specified length from open files. It can also be safely used for binary files. when a file is opened on a system that distinguishes binary files from text files (such as Windows), 'B' must be added to the mode parameter of the fopen () function '. The prototype of the function fread () is as follows:

The code is as follows:


String fread (int handle, int length) // read the opened file


This function reads a maximum of length bytes from the file pointer resource handle. When the length is read, or when the EOF is reached, or (for network streams) when a package is available, it will stop reading the file, depending on the first situation. This function returns the read content string. if it fails, FALSE is returned. The code for using a function is as follows:

The code is as follows:


<? Php
// Read the specified number of bytes from the file and save it to a variable.
$ Filename = "data.txt ";
$ Handle = fopen ($ filename, 'r') or die ("file opening failed ");
$ Contents = fread ($ handle, 100); // read 100 bytes from the file
Fclose ($ handle); // Close File Resources
Echo $ contents; // output the content read from the file

// Read all the content from the file to a variable. each time you read a part, you can read it cyclically.
$ Filename = "c: \ files \ somepic.gif ";
$ Handle = fopen ($ filename, 'RB') or die ("file opening failed"); // in read-only mode, 'B' is added to the mode'
$ Contents = "";
While (! Feof ($ handle) {// use feof () to determine the end of the file
$ Contents. = fread ($ handle, 1024); // read 1024 bytes each time
}
Fclose ($ handle); // Close File Resources
Echo $ contents; // output all the content read from the file

// Another method for reading all content from a file
$ Filename = "data.txt ";
$ Handle = fopen ($ filename, "r") or die ("file opening failed ");
$ Contents = fread ($ handle, filesize ($ filename); // read it together using the fielsize () function
Fclose ($ handle );
Echo $ contents;
?>

If you just want to read the content of a file into a string, you can use the file_get_contents () function, which has better performance than the above code. The file_get_contents () function is the preferred method for reading the file content into a string. if the operating system supports this function, the memory ing technology is used to improve the performance. The code for using this function is as follows:

The code is as follows:


<? Php
Echo file_get_contents ("data.txt"); // Read and output the content in the text file
Echo file_get_contents ("c: \ files \ somepic.gif"); // Read and output the content in the binary file
?>

② Functions fgets () and fgetc ()

Fgets () this function reads at most one row of content from open file resources at a time. The fgets () function is prototype as follows:

The code is as follows:


String fgets (int handle [, int length]) // returns a row from the opened file


The first parameter provides resources opened using the fopen () function. If the Second Optional parameter length is provided, the function returns length-1 bytes. Or return all content read before a line break or EOF. If you ignore the optional length parameter, the default value is 1024 characters. In most cases, this means that the fgets () function will encounter a line break before reading 1024 characters, so the next line will be returned for each successful call. If the Read fails, FALSE is returned. The code for using this function is as follows:

The code is as follows:


<? Php
$ Handle = fopen ("data.txt", "r") or die ("file opening failed"); // open the file in read-only mode
While (! Feof ($ handle )){
$ Buffer = fgets ($ handle, 4096); // read a row at a time
Echo $ buffer ."
"; // Output each flight
}
Fclose ($ handle );
?>

The fgetc () function only reads one character at the current pointer position in the opened file resource. If the end Mark EOF is encountered, FALSE is returned. The code for using this function is as follows:

The code is as follows:


<? Php
$ Fp = fopen('data.txt ', 'r') or die ("file opening failed ");
While (false! ==( $ Char = fgetc ($ fp ))){
Echo $ char ."
";
}
?>

③ Function file ()

This function is very useful. similar to file_get_contents (), you do not need to use the fopen () function to open the file. The difference is that the file () function can read the entire file into an array. Each element in the array corresponds to the corresponding row in the file. each element is separated by a linefeed, and the linefeed is still appended to the end of each element. In this way, you can use functions related to arrays to process the file content. The code for using this function is as follows:

The code is as follows:


<? Php
// Read the content in test.txt to an array and output
Print_r(file(test.txt ));
?>

④ Function readfile ()

This function can read the specified entire file, output immediately to the output buffer, and return the number of bytes read. This function does not need to use the fopen () function to open files. In the following example, the file content is easily output to the browser. The code is as follows:

The code is as follows:


<? Php
// Directly read the data in the data.txt file and output it to the browser
Readfile ("data.txt ");
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.