Home  >  Article  >  Backend Development  >  PHP file writing, reading and replacing content_PHP tutorial

PHP file writing, reading and replacing content_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:201631browse

Perfectly implement PHP writing, reading, and replacing file content. Let me explain first, mainly used:

  • fopen("File name.Extension", "Operation method")
  • fwrite(read file, "written file");
  • fclose(open object variable);
//写入文件
$str="This is a test from www.bkjia.comn"; 
// w表示以写入的方式打开文件,如果文件不存在,系统会自动建立
$file_pointer = fopen("aa.txt","a+");        
fwrite($file_pointer,$str);
fclose($file_pointer);
//读取文件
 $file_name="aa.txt";
 $fp=fopen($file_name,'r');
 while(!feof($fp))
 {
  $buffer=fgets($fp,4096);
  //替换文件
  $buffer = str_replace("bkjia","现代魔法",$buffer);
  $buffer = str_replace("This is a test","这是一个实例",$buffer);
  echo $buffer."<br />";
 }
 fclose($fp);

fopen()

The

fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened, and the second parameter specifies which mode to use to open the file.

Mode Description

  • r Read only. Start at the beginning of the file.
  • r+ read/write. Start at the beginning of the file.
  • w Write only. Opens and clears the contents of the file; if the file does not exist, creates a new file.
  • w+ read/write. Opens and clears the contents of the file; if the file does not exist, creates a new file.
  • a append. Opens and writes to the end of a file, or creates a new file if it does not exist.
  • a+ read/append. Maintain file contents by writing to the end of the file.
  • x Write only. Create new file. Returns FALSE if the file exists.
  • x+ read/write. Create new file. If the file already exists, returns FALSE and an error.

Note: If fopen() cannot open the specified file, it returns 0 (false).

feof()

Detect End-of-file

The feof() function detects whether the end of file (EOF) has been reached. The feof() function is useful when looping through data of unknown length. Note: In w, a and x modes, you cannot read open files!

if (feof($file)) 
	echo "End of file";

fgets()

fgets() function is used to read a file line by line from a file. After calling this function, the file pointer moves to the next line.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752504.htmlTechArticlePerfectly implements PHP writing, reading, and replacing file content. Let me explain first, mainly used: fopen("file name.extension", "operation mode") fwrite(read file, "written file"); fclos...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn