Home >Backend Development >PHP Tutorial >PHP file operations: reading and writing files

PHP file operations: reading and writing files

WBOY
WBOYOriginal
2016-07-25 08:59:271293browse
  1. @ $fp=fopen("http://bbs.it-home.org/abc123",'w');
  2. if (!$fp)
  3. {
  4. echo' file Does not exist ';
  5. exit;
  6. }
  7. ?>
Copy code

where the @ symbol means that PHP will suppress all errors generated by the current function call.

2, PHP reads files After opening the file in PHP, you need to read the file, usually using the fgets() function.

This function can read one line of content from the file at a time, and it will continue to read data until it encounters the newline character of this line, or the end symbol EOF of the full text.

The fgets() function can only read one line of data, so if you need to read all the data in the file, you must use a loop statement to complete it. for example:

  1. while (!feof($fp))
  2. {
  3. $bruce=fgets($fp);
  4. echo $bruce;
  5. }
Copy code

where the feof() function is used Check whether the file ends. The only parameter of this function is the file pointer (that is, $fp corresponds to the open file). Of course, in PHP you can also use the readfile() function to read the entire file at once. This function includes opening the file, reading the file and outputting it to the browser, and closing the file. for example:

  1. $bruce=readfile("http://bbs.it-home.org");
  2. echo $bruce;
  3. ?>
Copy code

3, PHP close file

Use the function fclose() to close the file.

Second, how to write data to file in PHP

Similar to PHP reading files, PHP writing files also requires: opening the file, writing data and closing the file. The method of opening and closing files has been explained above, but what about writing data to files in PHP?

Use the fwrite() function, such as fwrite(file path, write content):

  1. $bruce=fopen("http://bbs.it-home.org/","r");
  2. if(!$bruce)
  3. {
  4. echo'The file is not exists';
  5. exit;
  6. }
  7. while (!feof($bruce))
  8. {
  9. $rose=fgets($bruce);
  10. $james=fopen("index.htm","a");
  11. fwrite( $james,$rose);
  12. fclose($james);
  13. }
  14. fclose($bruce);
  15. ?>
  16. Generate the content of jbxue.com into a local file
Copy code

Other useful file functions: file_exists(): Check whether the file exists and return a Boolean value filesize(): Check the file size and can directly echo the output unlink(): Delete files. Note that there is no delete function in PHP.



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