The correct way to read files in PHP _php tips

Source: Internet
Author: User
Tags file handling fread readfile
Let's count the number of ways
One of the pleasures of dealing with modern programming languages like PHP is that there are a number of options available. PHP can easily win Perl's motto "There ' more than one way to do it" (not only a single method can do this), especially on file processing. But which of the many available options is the best tool to do the job? Of course, the actual answer depends on the goal of parsing the file, so it's worth taking the time to explore all the options.
Back to the top of the page
The traditional method of fopen
The Fopen method may be the most familiar to previous C and C + + programmers, because if you have used these languages, they are more or less the tools that you have mastered for years. For either of these methods, open the file by using the standard method of fopen (the function to read the data), and then close the file using Fclose, 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);
Although most programmers with years of programming experience are familiar with these functions, let me decompose these functions. Effectively perform the following steps:
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 you reach the end of the file and print each line while reading.
Closes the file.
With these steps in mind, I'll review each of the file functions used here.
fopen
The fopen function creates a connection to the file. The reason I say "create a connection" is because, in addition to opening the file, fopen can open a URL: $fh = fopen ("HTTP://127.0.0.1/", "R");
This line of code creates a connection to the above page and allows you to start reading it as if you were reading a local file.
Note: the "R" used in fopen will indicate that the file is opened as read-only. Because writing data to a file is not covered in this article, I will not list all the other options. However, if you are reading from a binary file to obtain Cross-platform compatibility, you should change "R" to "RB". You'll see an example of this later.
Feof
The feof command detects whether you have read to the end of the file and returns True or False. The loop in Listing 1 continues until you reach the end of the file "MyFile". Note: If the URL is read and the socket times out because no more data can be read, feof also returns FALSE.
Fclose
Skip forward to the end of Listing 1, and fclose will implement the function opposite to fopen: it closes the connection to the file or URL. After you perform this function, you will no longer be able to read any information from a file or socket.
Fgets
If you jump back a few lines in Listing 1, you get to the core of the 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 prints the entire file in fine detail.
If you decide to limit the size of the processed data blocks, you can add a parameter to the fgets to limit the maximum length of the line. For example, use the following code to limit the line length to 80 characters: $string = fgets ($file _handle, 81);
Recall the Terminator at the end of the "I" string in C to set the length to a number larger than the actual desired value. Thus, if 80 characters are required, the above example uses 81. You should develop the following habits: Add the extra character as long as the line limit is used for this function.
Fread
The Fgets function is available in more than one by one file read functions. It is a more commonly used function, because row-by-line parsing usually makes sense. In fact, several other functions can also provide similar functionality. However, you do not always need to parse line by row.
Then you need to use fread. The Fread function is slightly different from the fgets target: it tends to read information from binary files (that is, files that are not primarily human-readable text). Because the concept of "row" has nothing to do with binary files (logical data structures are typically not terminated by new rows), you must specify the number of bytes to read. $fh = fopen ("MyFile", "RB");
$data = Fread ($file _handle, 4096);
Using binary data
Note: An example of this function already uses a slightly different parameter than fopen. When working with binary data, always remember to include the B option in fopen. If you skip this, the microsoft®windows® system may not be able to process files correctly because they will handle 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 development, 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 the file size is not more than 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 is longer than this value, you can only use loops to read the rest of the content.
fscanf
Back to string processing, 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 string used by this function is described in many places (such as php.net), so it is no longer necessary to repeat it here. It can be said that string formatting is extremely flexible. It is worth noting that all fields are placed in the return value of the function. (in C, they are all passed as parameters.) )
Fgetss
The FGETSS function differs from traditional file functions and enables you to better understand the power of PHP. The function is similar to the Fgets function, but will remove any HTML or PHP tags found, leaving only plain text. View the HTML file as shown below.
Listing 2. Sample HTML File
<body>
<p>if you understand what "cause there ain ' t one for to give you no pain"
means then you listen to too much of the band America</p>
</body>
Then filter it through the FGETSS function.
Listing 3. Using FGETSS
$file _handle = fopen ("MyFile", "R");
while (!feof ($file _handle)) {
echo = FGETSS ($file _handle);
}
Fclose ($file _handle);
The following is the output: my title
If you are understand what "cause there ain ' t one for to give you no pain"
means then you 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 do not need to use variables to get the data.
Nonlinear file processing: 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. Then you need fseek. Fseek ($fh, 0);
The above example jumps back to the beginning of the file. If you don't need to return completely--we can set the return kilobytes--then we can write this: 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 jump back 100 bytes using the following code: Fseek ($FH, -100, seek_cur);
You should use Seek_end if you want to jump back to the first 100 bytes of the end of the file. Fseek ($FH, -100, seek_end);
After you reach the new location, you can use Fgets, fscanf, or any other method to read the data.
Note: You cannot use fseek for file handling that references URLs.
Back to the top of the page
Extract entire file
Now we'll touch on some of PHP's more unique file-handling capabilities: Working with chunks of data in one or two rows. For example, how do 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 this process be made simpler? Using fgetcontents makes the process super simple, which puts the entire file in a string. $my _file = file_get_contents ("myFileName");
echo $my _file;
Although it is not the best practice, this command can be written more concisely as: Echo file_get_contents ("myFileName");
This article mainly describes how to work with local files, but it is 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 are sure to look at the command and say, "That's still too much effort." The PHP developers agree 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 required), try: @readfile ("HTTP://127.0.0.1/");
Of course, if you do need to parse a file, a single string returned by file_get_contents may 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 since there's already a good function to do this for you, why go through all this trouble? PHP's file () function completes this step: it returns an array of strings that are divided into rows. $array = File ("MyFile");
It should be noted that the above two examples are slightly different. Although the split command deletes a new row, the new row will still be appended to the string in the array when the file command (like the fgets command) is used.
But the power of PHP is much more than that. You can use Parse_ini_file in one command to parse an entire PHP-style. ini file. The Parse_ini_file command accepts a file similar to that shown in Listing 4.
Listing 4. Sample. ini file
; Comment
[Personal Information]
Name = "King Arthur"
Quest = to seek the Holy Grail
Favorite color = Blue
[More Stuff]
Samuel Clemens = Mark Twain
Caryn Johnson = Whoopi Goldberg
The following command dumps this file to an array and then prints it: $file _array = Parse_ini_file ("Holy_grail.ini");
Print_r $file _array;
The following output is the result:
Listing 5. Output
Array
(
[Name] => King Arthur
[Quest] => to seek the Holy Grail
[Favorite color] => Blue
[Samuel Clemens] => Mark Twain
[Caryn Johnson] => Whoopi Goldberg
)
Of course, you may notice that this command incorporates 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 the process_sections to True. $file _array = Parse_ini_file ("Holy_grail.ini", true);
Print_r $file _array;
And you will get the following output:
Listing 6. 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 will put the data into a multidimensional array that can be easily parsed.
This is just the tip of the iceberg for PHP file processing. More complex functions, such as Tidy_parse_file and Xml_parse, can help you work with HTML and XML documents, respectively. For details on the use of these special functions, see Resources. If you want to work with those types of files, those references are worth looking at, but you don't have to think too much about each type of file that you might encounter in this article, and here are some good general rules for handling the functions described so far.
Back to the top of the page
Best practices
Never assume that everything in the program will run as planned. For example, what if the file you are looking for has been moved? What if the permission has been changed and cannot read its contents? You can check these issues in advance by using file_exists and is_readable.
Listing 7. Using File_exists and Is_readable
$filename = "MyFile";
if (file_exists ($filename) && is_readable ($filename)) {
$fh = fopen ($filename, "R");
# processing
Fclose ($FH);
}
In practice, however, it may be too cumbersome to use such code. The return value of processing fopen is simple and more accurate. if ($fh = fopen ($filename, "R")) {
# processing
Fclose ($FH);
}
Fopen returns FALSE because of a failure, which ensures that file processing is performed only if the file is successfully opened. Of course, if the file does not exist or is unreadable, you can expect a negative return value. This will enable this check to check for any problems that may be encountered. In addition, if the open fails, you can exit the program or have the program display an error message.
Like the fopen function, the file_get_contents, file, and ReadFile functions return False when they fail to open or process a file. The fgets, FGETSS, Fread, fscanf, and fclose functions also return False when an error occurs. Of course, you may have processed the return values of these functions, except for fclose. When you use fclose, you do not normally have to check the return value of fclose, even if the file processing does not shut down properly.
Back to the top of the page
It's up to you to choose
PHP does not lack the efficient way to read and parse files. Typical functions, such as fread, may be the best choice most of the time, or you may find yourself attracted to a more readfile simplicity when the ReadFile just meets the needs of the task. It actually depends on the action you want to complete.
If you are dealing with large amounts of data, FSCANF will be able to prove its worth and be more efficient than using the file with split and sprintf commands. Conversely, using file, file_get_contents, or ReadFile may be more appropriate if you want to echo a large amount of text that is only slightly modified. This may be the case when using PHP for caching or creating an expedient proxy server.
PHP provides you with a lot of tools for working with files. Learn more about these tools and what tools are best for the projects you want to work with. You already have a lot of choices, so make good use of them to enjoy the fun of working with PHP files.

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.