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