The correct way to read data in PHP

Source: Internet
Author: User
Tags file handling readfile
The correct way to read files in PHP

Learn how to use PHP's various file functions. View basic file functions such as fopen, Fclose, and feof, and learn about read functions such as fgets, FGETSS, and fscanf. and found a function to process the entire file with one or two lines of code.

Let's figure out how many ways

One of the pleasures of dealing with modern programming languages such as PHP is that there are a number of options available. PHP can easily win Perl's motto "There's more than one ways to do it" (not the only way it can be done), especially in file processing. But in so many available options, which is the best tool to complete 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 options.


The traditional method of fopen

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);

Although most programmers with years of programming experience are familiar with these functions, let me break them down. Perform the following steps effectively:
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.

Remembering these steps, I'll review each of the file functions used here.

fopen

The fopen function creates a connection to the file. I say "create connection" because, in addition to opening the file, fopen can also 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 like a local file.

Note: the "R" used in fopen will instruct the file to open as read-only. Because writing data to a file is beyond the scope of this article, I will not list all the other options. However, if you are reading from a binary file for cross-platform compatibility, you should change "R" to "RB". You'll see an example of this later.

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);

??? ??? Using binary data

Note: An example of this function has 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? The system may not be able to process the files correctly because they will handle new rows in different ways. What if I'm working on Linux? System (or some other UNIX?) Variant), then this may seem to be of little relevance. 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

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 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.) )

Fgetss

The 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.

Listing 2. Sample HTML file??? ??? ??? ???

???<title>My Title</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


???


It is then filtered by the FGETSS function.

Listing 3. 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.


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. The Parse_ini_file command accepts files similar to those shown in Listing 4.

Listing 4. Example. 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 the 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 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:

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.

For PHP file processing, this is just the tip of the iceberg. More complex functions, such as Tidy_parse_file and Xml_parse, can help you work with HTML and XML documents, respectively. See Resources for details on the use of these special functions. If you want to work with those types of files, those references are worth looking at, but you don't have to over-consider each of the types of files you might encounter in this article, and here are some good general rules for dealing with the functions described so far.

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 permissions have been changed and the contents cannot be read? You can pre-check these issues by using file_exists and is_readable.

Listing 7. Use File_exists and is_readable??? ??? ??? ???
$filename = "MyFile";
if (file_exists ($filename) && is_readable ($filename)) {
??? $fh = fopen ($filename, "R");
??? # processing
??? Fclose ($FH);
}

However, in practice, 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 will return False due to failure, which will ensure that file processing is performed only when 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 all possible problems. In addition, if the open fails, you can exit the program or let the program display an error message.

Like the fopen function, the file_get_contents, file, and ReadFile functions return False if they fail to open or process the file. The fgets, FGETSS, Fread, fscanf, and fclose functions also return False on error. Of course, you may have already 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 file processing does not close properly.

It's up to you to choose

PHP does not lack the effective method of reading and parsing files. Typical functions, such as fread, may be the best choice for most of the time, or you may find yourself more attracted to ReadFile simplicity when ReadFile just enough to meet the needs of the task. It actually depends on the action you want to complete.

If you are working with a large amount of data, FSCANF will be able to prove its worth and be more efficient than using the split and sprintf commands that are included with file. Conversely, using file, file_get_contents, or ReadFile may be more appropriate if you want to echo a large amount of text that has only been modified slightly. 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 see which tools are best suited for the projects you want to work with. You already have a lot of choices, so make good use of them to enjoy working with PHP files.

?

Reprinted from: http://www.ibm.com/developerworks/cn/opensource/os-php-readfiles/index.html

  • Related Article

    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.