The correct way to read files in PHP Summary, don't forget to close the file

Source: Internet
Author: User
Tags file handling fread readfile
The fopen method is probably the most familiar to the previous C and C + + programmers, because if you have used these languages, they are more or less a tool that you have mastered for years. For any of these methods, open the file by using the standard method of fopen (the function used to read the data) and then use Fclose to close the file, as shown in Listing 1.

Listing 1. Open and read files with fgets

$file _handle = fopen ("MyFile", "R"); while (!feof ($file _handle)) {$line = fgets ($file _handle); echo $line;} fclose ($file _handle);

Open the file. $file _handle stores a reference to the file itself.
Check to see if you have reached the end of the file.
Continue reading the file until the end of the file is reached, and each line is printed while reading.
Close the file.
Remember these steps.

Feof
The feof command detects if you have read the end of the file and returns True or False. The loop in Listing 1 will continue until you reach the end of the file "MyFile". Note: If you read a URL and the socket times out because no longer has any data to read, feof will also return False.
Fclose
Jumping forward to the end of Listing 1, Fclose will implement the opposite function of fopen: It will close the connection to the file or URL. After you execute this function, you will no longer be able to read any information from a file or socket.
Fgets
Jumping back a few lines in Listing 1, you reached the core of file processing: actually read the file. The Fgets function is the preferred weapon for handling the first example. It extracts a row of data from the file and returns it as a string. After that, you can print or otherwise process the data. The example in Listing 1 will print the entire file in fine detail.
If you decide to limit the size of the processing data block, you can add a parameter to the fgets to limit the maximum number of lengths. For example, use the following code to limit the length of a line to 80 characters: $string = fgets ($file _handle, 81);
Recall the end terminator of the "\" string in C, set the length to a number higher than the actual desired value. Thus, if 80 characters are required, the above example uses 81. You should get into the habit of adding this extra character whenever you use a row limit on this function.
Fread
The Fgets function is available in more than one by one file read functions. It is a more common function because line-by-row parsing usually makes sense. In fact, several other functions can also provide similar functionality. However, you do not always need line-by-row parsing.
At this point, you need to use fread. The Fread function is slightly different from the processing target of fgets: it tends to read information from a binary file (that is, a file that does not primarily contain human-readable text). Because the concept of "line" is not related to binary files (the logical data structure is not usually terminated by new lines), you must specify the number of bytes to read in. $fh = fopen ("MyFile", "RB");

$data = Fread ($file _handle, 4096);
<?php$file_path = "Test.txt", if (file_exists ($file _path)) {$fp = fopen ($file _path, "R"); $str = Fread ($fp, FileSize ($file _path));//Specify the read size, where the entire contents of the file are read echo $str = Str_replace ("\ r \ n", "<br/>", $str);}? 

Using binary Data
Note: Examples of this function have used a slightly different parameter than fopen. When working with binary data, always remember to include the B option in fopen. If you skip this, Microsoft Windows systems may not be able to handle the files correctly because they will process the new rows in different ways. If you are dealing with a Linux system (or some other UNIX variant), this may seem like nothing. But even if it's not for Windows, doing so will get good cross-platform maintainability and a good habit to follow.
The above code reads 4,096 bytes (4 KB) of data. Note: No matter how many bytes are specified, Fread will not read more than 8,192 bytes (8 KB).
Assuming that the file size does not exceed 8 KB, the following code should be able to read the entire file into a string. $fh = fopen ("MyFile", "RB");
$data = fread ($fh, FileSize ("myfile"));
Fclose ($FH);
If the file length is greater than this value, you can only use loops to read the rest of the content.
fscanf
returns to string processing, and fscanf also follows the traditional C file library functions. If you are unfamiliar with it, FSCANF will read the field data from the file into the variable. List ($field 1, $field 2, $field 3) = fscanf ($fh, "%s%s");
The format strings used by this function are described in many places (such as php.net), so we will not repeat them here. It can be said that string formatting is extremely flexible. It is important to note that all fields are placed in the function's return value. (in C, they are all passed as parameters.) The
Fgetss
Fgetss function differs from traditional file functions and gives you a better understanding of the power of PHP. The function is similar to the Fgets function, but will remove any HTML or PHP markup found, leaving only plain text. View the HTML file as shown below.
Sample HTML file


It is then filtered by the FGETSS function.
Using FGETSS

$file _handle = fopen ("MyFile", "R"); while (!feof ($file _handle)) {echo = FGETSS ($file _handle);} fclose ($file _handle);

Here is the output: My title
If you understand the "cause there ain ' t one for give you no pain"
Means then your listen to too much of the band America
Fpassthru function
Regardless of how you read the file, you can use Fpassthru to dump the rest of the data to the standard output channel. Fpassthru ($FH);
In addition, this function prints the data, so you don't need to use variables to get the data.
Non-linear file handling: Jump Access
Of course, the above functions only allow sequential reading of files. More complex files may require you to jump back and forth to different parts of the file. At this time it is useful to fseek. Fseek ($fh, 0);
The above example jumps back to the beginning of the file. If you do not need to return completely--we can set the return kilobytes--and then we can write: fseek ($FH, 1024);
Starting with PHP V4.0, you have some other options. For example, if you need to jump 100 bytes forward from the current position, you can try using: fseek ($FH, seek_cur);
Similarly, you can use the following code to jump back 100 bytes: fseek ($fh, -100, seek_cur);
If you need to jump back to the top 100 bytes at the end of a file, you should use Seek_end. Fseek ($FH, -100, seek_end);
After you reach the new location, you can read the data using Fgets, FSCANF, or any other method.
Note: You cannot use fseek for file processing that references URLs.

Back to top of page
Extract the entire file
Now, we'll be exposed to some of the more unique file handling features of PHP: Working with chunks of data in one or two rows. For example, how can I extract a file and display all of its contents on a Web page? OK, you see an example of fgets using loops. But how can you make this process easier? Using fgetcontents will make the process super-simple, and the method will put the entire file into a string. $my _file = file_get_contents ("myFileName");
echo $my _file;
Although it is not the best practice, this command can be more succinctly written as: Echo file_get_contents ("myFileName");
This article focuses on how to work with local files, but it's worth noting that you can also use these functions to extract, echo, and parse other Web pages. Echo file_get_contents ("HTTP://127.0.0.1/");
This command is equivalent to: $fh = fopen ("HTTP://127.0.0.1/", "R");
Fpassthru ($FH);
You will definitely look at this command and think, "That's still too much effort." The PHP developer agrees with you. Therefore, the above command can be shortened to: ReadFile ("HTTP://127.0.0.1/");
The ReadFile function dumps the entire contents of a file or Web page to the default output buffer. By default, this command prints an error message if it fails. To avoid this behavior (if necessary), try: @readfile ("HTTP://127.0.0.1/");
Of course, if you do need to parse the file, the single string returned by File_get_contents can be a bit overwhelming. Your first reaction might be to break it down with the split () function. $array = Split ("\ n", file_get_contents ("myfile"));
But now that there's a good function for you to do this, why do you have to do this so much? PHP's file () function does this in one step: it returns an array of strings that are divided into several rows. $array = File ("MyFile");
It should be noted that the above two examples are slightly different. Although the split command deletes new rows, when the file command is used (as with the fgets command), the new row will still be appended to the string in the array.
However, PHP is far more powerful than this. You can use Parse_ini_file to parse an entire PHP-style. ini file in a single command.
Of course, you may notice that this command merges the various parts. This is the default behavior, but you can easily fix it by passing the second argument to Parse_ini_file: Process_sections, which is a Boolean variable. Set Process_sections to True.

$file _array = Parse_ini_file ("Holy_grail.ini", true); Print_r $file _array;

And you will get the following output:

Array ([personal information] = = Array ([name] = King Arthur [Quest] + to seek the Holy Grail [favorite Color ] + Blue) [more stuff] = = Array ([Samuel Clemens] + Mark Twain [Caryn Johnson] = Whoopi Goldberg))
<?php$file_path = "Test.txt", if (file_exists ($file _path)) {$fp = fopen ($file _path, "R"); $str = "";  $buffer = 1024;//reads 1024 bytes at a time (!feof ($fp)) {//loops through the entire file $str. = Fread ($fp, $buffer);} $str = Str_replace ("\ r \ n", "<br/>", $str); echo $str;}? 

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.