PHP Read File summary _php tutorial

Source: Internet
Author: User
Tags file handling php read file
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 "Theres more than one ways to do it" (not just a way of doing it), 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 fopen can also open a URL in addition to opening the file:

$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-of-string terminator in C, which sets 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, the microsoft®windows® system may not be able to handle the 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, 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


My Title

If you understand the "cause there aint no one for the 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 aint no one for the 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 location, you can try using:

Fseek ($FH, seek_cur);

Similarly, you can jump backwards by 100 bytes using the following code:

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, you can write this command more concisely 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://www.bkjia.com/PHPjc/478851.html www.bkjia.com true http://www.bkjia.com/PHPjc/478851.html techarticle let's figure out how many ways to deal with modern programming languages such as PHP are a lot of options available. PHP can easily win Perl's motto "There ...

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