PHP file Operations (1)--open/Read files

Source: Internet
Author: User
Tags fread

1. Open File (fopen)

Syntax:resource $fp =fopen (file address, mode), returns the file pointer (filename pointer)

Mode Meaning
R Read-only
W Write (empty rewrite)
A Additional
$fp fopen ('./aa.txt ', ' R ');   // Read-only $fp fopen ('./aa.txt ', ' W ');   // write (empty rewrite) $fp fopen ('./aa.txt ', ' a ');   // Append

2. Read the file ( fread,file_get_contents)

Syntax:string fread ($fp , File size )

File_get_contents to read the entire file into a string

Syntax:string file_get_contents ( string $filename)

<?PHP$filename= './aa.txt ';Echo"<br><br>****** first method of reading ********<br>";$fp=fopen($filename, "R");$con=fread($fp,filesize($filename));//by default, the content displayed to a Web page is not wrapped, and you need to replace the line break \ r \ <br/>$con=Str_replace("\ r \ n", "<br/>",$con);Echo"$con";//Close Pointerfclose($fp);Echo"<br><br>****** Second Read method, loop read (for large files) ********<br>";$fp=fopen($filename, "R");//set Buffer to read 1024 bytes at a time$buffer= 1024;//determine if the file pointer is at the end of the file while(!feof($fp)) {    //Read    $con=fread($fp,$buffer); //Replace line break    $con=Str_replace("\ r \ n", "<br/>",$con); Echo"$con";}//Close Pointerfclose($fp);Echo"<br><br>****** third method of reading ********<br>";$con=file_get_contents($filename);//Replace line break$con=Str_replace("\ r \ n", "<br/>",$con);Echo"$con";

Results:

3.fgets (): Reads a line and moves the pointer down one line

$filename = "Aa.txt", $fp = fopen ($filename, ' R '), while (!feof ($fp)) {echo fgets ($fp). " <br/> ";}

Results:

$filename = "Aa.txt"; fseek ($fp, 0);  Move the file pointer to the front of the file while (!feof ($fp)) {echo fgets ($fp). " <br/> ";}

Results:

4.GETC (): Gets a character

$filename = "Aa.txt"; $fp = fopen ($filename, ' R '), while (!feof ($fp)) {//Gets a Chinese character, consumes 3 bytes of echo fqetc ($FP). " <br/> ";}

  

PHP file Operations (1)--open/Read 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.