PHP file Write and read text details

Source: Internet
Author: User
This article mainly introduces the PHP file to write and read the graphic details, interested in the friend's reference, I hope to help you. Article outline:

A Basic ideas for implementing file reads and writes

Two To open a file using the Fopen method

Three File read and file write operations

Four To close a file using the Fclose method

Five Move the file pointer

Six Carriage return and line feeds under Windows and UNIX

A Basic ideas for implementing file reads and writes:

1. Open file by fopen method: $fp =fopen (/* parameter, Parameter */), FP is resource type
2. File read or file write operation (the function used here takes the $FP returned in 1 as the parameter)
3. Call Fclose ($FP) to close the closing file

Two: Open the file using the Fopen method

fopen (file path [string], open mode [string])

The first parameter of <1>fopen is the file path
How to write a file path: 1 absolute path, 2 relative path

1 Absolute path:

Small partners working under Windows should be familiar with the path delimiter under Windows as "\" instead of "/", but we cannot write the path with the "\" delimiter

What happens if we write the path with the "\" delimiter?


<?php   $fp = fopen ("C:\wamp64\www\text.txt", ' w ');? >


Error after running, prompt path parameter is invalid


So we're going to replace the delimiter "\" with "/":


<?php  $fp = fopen ("C:/wamp64/www/text.txt", ' w ');? >


Operation without error, indicating that the parameters are valid.

"Attention" fopen function does not understand the "\" delimiter, if you want to use "\", then you want to use escape, such as written: "C:\\wamp64\\www\\text.txt" This is also possible, the function can understand, will not error. But even then, "\" is not recommended because "/" cannot be recognized under OS (MAC) "\"

The conclusion of this section is that it is recommended to stick with the "/" as a delimiter

2. Relative path:

The previous section describes the absolute path, but this brings another problem: the server directory structure may have a large change, then the original written absolute path will be all rewritten, such as the target file path on my computer is c:/wamp64/www/ Text.txt, what if I rename the www folder to Penghuwan? The path parameter that was originally written is invalidated. So we've introduced a relative path to the notation:


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' w ');? >


$_server is a super global variable for PHP (accessible anywhere in the code, type is an array), and is available to the server's default root by $_server[' Document_root ')

The default root directory of the server can be modified by php.ini (this can be self-Baidu)

$_server[' Document_root ' is here equivalent to C:/wamp64/www

This section concludes that relative paths are recommended

The second parameter of <2>fopen is open mode

After setting the open mode, we set the permissions for the following read and write operations:

Some of the most basic patterns:

"R": can only read files, cannot write to file (write operation is ignored)
"W": can only write to file, cannot read file (read operation is ignored)
"A": Append only files, similar to "w", The difference is "W" Delete the original content, "a" does not delete the original content, only append content


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' W ');  Fwrite ($fp, ' write in write mode ');  Fclose ($FP);? >


After you have set permissions on the write operation, you can write the file normally.

Open C:/wamp64/www/text.txt after running:

This time we set the permission to read-only and try to write the text: ' Write in read-only mode '


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');  Fwrite ($fp, ' write in read mode ');  Fclose ($FP);? >


After running open c:/wamp64/www/text.txt, found that the contents of the file did not change, the operation is ignored because the appropriate permissions are not set

On the open mode of the network data, I think we most likely to find this table: (Picture from the web)

Very comprehensive, but I think this watch is not very friendly to the novice, let people look after the cloudy. R is read-only, W is write-only (the original content is completely deleted), A is appended (do not delete the original content), which is well understood.

But r+,w+, and the difference between a + and the connection is really too vague ah. Here I would like to give a detailed talk about r+,w+, and A + three of the difference and contact:

First, the r+,w+, and A + are readable and writable, and the way to read is the same, the key lies in the different ways of writing:

r+: from the file [header] [overwrite] the original content ([Do not delete] the original content);

A +: from the file [tail] [Append] content ([Do not delete] the original content);

w+: [Completely delete] The original content, and then [Add] new content

Here I turn to the above conclusion, first we do not write when the text is "I am initialized value" (meaning I am the initial value)

Write text "r+ mode" using r+ mode


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' r+ ');  Fwrite ($fp, ' r+ mode ');  Fclose ($FP);? >


After running and then opening the text, I find "I am in" is covered by "r+ mode":

Write the text "A + mode" with a + pattern

Based on the initial text of "I am initialized value" We run the following code:


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' A + ');  Fwrite ($FP, ' A + mode ');  Fclose ($FP);? >



I am initialized value is not deleted and overwritten, but is appended with a + mode for this new section of text

After running multiple times:

• Write text "w+ mode" using w+ mode

Based on the initial text of "I am initialized value" We run the following code:


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' w+ ');  Fwrite ($fp, ' w+ mode ');  Fclose ($FP);? >


After the operation, we found that "I am initialized value" has been deleted, and then added "w+ mode" this new text

"Note" r+,a+,w+ there is another difference is that the a+,w+ file does not exist when the file is created, r+ file does not exist The Times wrong

"Spit Groove": About the difference between r+ and w+,a+, I found on the internet, including the World Wide Web and various blog posts and the "PHP Bible" on the various materials, found to be a piece of the past, which is why I wrote this article

Three File read and file write operations

Let's talk about some of the more important functions:

file_exists (): Determines whether a file exists, returns a Boolean value

filesize (): Determines the size of a file, returns the number of bytes of the file, the integer number

unlink (): Delete a file

Write file

Fwrite (Resource file Object [string], write as [string]), the resource file object is the parameter returned by the Fopen method, the resource type, which can be written in W (or w+,a+,r+)

Already have the above example, here will not put the demo

Read file

Here are the contents of the file we want to read:


There are several ways to read files:

1. Read one byte of data at a time fgetc ()

2. Data fread () reading the specified number of bytes at a time

3. read one row of data at a time fgets ()/fgetcsv ()

4. Read all data at once fpassthru ()/file ()

1. Read one byte at a time--get a single byte by Fgetc ()


<?php   $DOCUMENT _root = $_server[' document_root ');   $fp = fopen ("$DOCUMENT _root/text.txt", ' r ');//Open File   if (file_exists ("$DOCUMENT _root/text.txt")} {//read content when file exists While     (!feof ($fp)) {//Determines whether the file pointer reaches        the end $c = fgetc ($FP);//The file pointer moves backwards by one echo $c each time fgetc () is executed        ;//output gets to the byte      }    }   Fclose ($FP);//Close File?>


Run:

Note: Whether you enter output in text format or in binary format, fgetc () gets a byte at a time instead of a character !

In the example above, we are outputting one output at a time, so let's just do the output once to see what the results are:


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');  echo fgetc ($FP);//Only once output  close ($fp); >


The result of the operation is as follows, we get not the Chinese character "I", but a garbled, in fact, this garbled is a byte


<?php   $DOCUMENT _root = $_server[' document_root ');   $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');   echo fgetc ($FP);//Output   echo fgetc ($fp)   three times in succession; echo fgetc ($fp);   Fclose ($FP);? >


2. Read multiple bytes at once-through the Fread () method:


<?php  $DOCUMENT _root = $_server[' document_root ');  $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');  Echo Fread ($FP, 3);//output three bytes at a time i.e. one Kanji character (UTF-8)  fclose ($fp);? >


Operation Result:


Change to:


Echo Fread ($FP, 6);


The result of the operation is as follows, output 6 bytes or two kanji characters (UTF-8)

3. Read one line at a time--get a line of content by Fgets ()


<?php    $DOCUMENT _root = $_server[' Document_root '    ) $fp = fopen ("$DOCUMENT _root/text.txt", ' r ');//Open File    if (file_exists ("$DOCUMENT _root/text.txt")) {//When the file exists, the content is read while     (!feof ($fp)) {//Determines whether the file pointer reaches the end       $line = fgets ($fp);//Returns a line of text and moves the file pointer to the next line of the head       echo $line. " <br/> ";//output gets to a line of text     }    }    fclose ($FP);//Close File?>


Fgets () actually has a second parameter, which specifies the maximum number of bytes that can be read per line (note that the number of bytes is not a character):

"Note" Under UTF-8 encoding Kanji 3 Bytes, 1 bytes

Below I modify the line above, the code to get the maximum number of characters per row is 3 (also known as the number of bytes 9)


$line = fgets ($fp, 10);


Demo:

"Note": Here I fgets () the second parameter is 10, why is 10? Because

1. The length of this place is calculated by the number of bytes

2. A Chinese character occupies 3 bytes. Fgets ($FP, 10) represents a maximum read of 10-1 = 9 bytes

4. Read all files at once--fpassthru () or file ()?

Fpassthru () will read the file and output directly (no process)


<?php   $DOCUMENT _root = $_server[' document_root ');   $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');   Fpassthru ($FP);   Fclose ($FP);? >


Operation Result:

"Attention" one thing to note here is that we did not get the return value from Fpassthru ($FP) and then echo to the page, which means that the method would force the output to get the content, rather than returning the text as the method in the previous example, allowing us to save it to the variable to output it

Saves everything read into an array, each array element is a row of content--fille ()


<?php  $DOCUMENT _root = $_server[' document_root ');  $file _array = File ("$DOCUMENT _root/text.txt");//Fetch to the array of files  foreach ($file _array as $value) {//output array element    echo $value. " <br/> ";  }? >


"Note": Here we do not need to write fopen and fclose Oh! That means the file () method has done this for us.

Four To close a file using the Fclose method

Fclose () returns a Boolean value that successfully shuts down to true, and the shutdown fails to false (the failure condition rarely occurs, regardless)

Do you want to close the file after opening it?

1 even if not handwritten fclose, after the execution of PHP script, will automatically close the file

2 but in a long-executed script, if you do not write closed file fclose (), in the case of file lock will cause the operation of blocking, so, write fclose is a good habit

Five Move the file pointer

We call the above function of the read file, in fact, is based on the file pointer to print, each read a byte of content, the file pointer will move backward a length of bytes, until the file is read the maximum byte length


<?php     $DOCUMENT _root = $_server[' document_root ');     function Print_file_pointer ($FP) {//defines the position of a print file pointer       to echo "<br/>//at this time the position of the file pointer:";       Echo Ftell ($fp). " <br/> ";     }     $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');     echo fgetc ($FP);//continuous output of three bytes via fgetc     echo fgetc ($fp);     echo fgetc ($fp);     Print_file_pointer ($FP);//Prints the position of the file pointer at the moment          Echo fread ($FP, 6),//outputs 6 bytes     Print_file_pointer ($fp) via fread once;// Prints the position of the file pointer at the moment          Echo fgets ($FP);//output a full line of     Print_file_pointer ($fp) through fgets;//Print the position of the file pointer          fpassthru ($FP); One-time output all content     Print_file_pointer ($fp);//print the position of the file pointer at the moment          fseek ($fp, 33);//move the file pointer to a 33-byte position     Print_file_ Pointer ($fp);//print the position of the file pointer at the moment          Rewind ($FP);//Make the file pointer move to a 0-byte position (the initial position)     Print_file_pointer ($FP);//print the position of the file pointer at the moment $ Fclose ($FP);? >


Demo:

So we need to understand correctly the function of fgets (), Fpassthru ():

fgets (): from the position of the current file pointer to the end of the bank's data, instead of necessarily outputting an entire line

fpassthru (): data from the position of the current file pointer to the end of the entire content, rather than necessarily outputting all the data

But here you may have questions about why the position of the pointer after "Bay" will be 17 instead of 15? Supposedly, the output "I call Peng Lake" These 5 characters accounted for 3*5 = 15 bytes, the extra 17-15 = 2 bytes is what?

The extra two bytes are the carriage return newline character under Windows \n\r

\ n is newline, takes one byte, \ r is carriage return, takes up one byte, in six I will introduce

Six Carriage return and line feeds under Windows and UNIX


<?php   $DOCUMENT _root = $_server[' document_root ');   $fp = fopen ("$DOCUMENT _root/text.txt", ' R ');   while (!feof ($fp)) {    echo fgets ($fp);    Echo Ftell ($FP);   }   Fclose ($FP);? >


When we hit the ENTER key under Windows, it was equivalent to typing \n\r, so "My name is Peng Bay" of 15 bytes + 2 bytes of "\n\r" = 17 bytes

Under the Mac is not the same: when you hit the return, it is equivalent to just type \ n, so "My name is Peng Bay" of 15 bytes + "\ n" of 1 bytes = 16 bytes

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.