php读取文件与写入文件方法实例

在php中读取文件我们需要使用file_get_contents或fopen来打开文件然后再读取了,file_get_contents函数读文件比fopen要方便,写文件需要fopen函数与file_put_contents或fwrite合作才可以实例下面我来介绍下.

php写文件的方法

实例一,代码如下:

  1. $filename = 'test.txt';
  2. $filename = dirname ( __FILE__ ) . '/' . $filename;
  3. if (file_exists ( $filename )) {
  4. if (! is_writable ( $filename )) {
  5. exit('is not writable');
  6. }
  7. $handle = fopen ( $filename, "a+b" );
  8. $content = 'this is test words';
  9. $content .= "n";
  10. fwrite($handle, $content);
  11. fclose ( $handle );
  12. } else {
  13. exit('file is not exists');
  14. }

实例二,代码如下:

  1. $filename = 'test.txt';
  2. $filename = dirname ( __FILE__ ) . '/' . $filename;
  3. if (file_exists ( $filename )) {
  4. if (! is_writable ( $filename )) {
  5. exit('is not writable');
  6. }
  7. $content = 'this is test words';
  8. $content .= "n";
  9. file_put_contents($filename, utf8_encode($content));
  10. } else {
  11. exit('file is not exists');
  12. }

php读取文件

实例一,代码如下:

  1. $filename = 'test.txt';
  2. $filename = dirname ( __FILE__ ) . '/' . $filename;
  3. if (file_exists ( $filename )) {
  4. if (! is_readable ( $filename )) {
  5. exit('is not readable');
  6. }
  7. $contents = file_get_contents($filename);
  8. $contents = explode("n", $contents);
  9. print_r($contents);
  10. } else {
  11. exit('file is not exists');
  12. }

实例二,代码如下:

  1. $filename = 'test.txt';
  2. $filename = dirname ( __FILE__ ) . '/' . $filename;
  3. if (file_exists ( $filename )) {
  4. if (! is_readable ( $filename )) {
  5. exit('is not readable');
  6. }
  7. $handle = fopen ( $filename, "rb" );
  8. $contents = fread($handle, filesize ($filename));
  9. //$contents = stream_get_contents($handle); // 也可以用方法替换上一行
  10. $contents = explode("n", $contents);
  11. fclose ( $handle );
  12. print_r($contents);
  13. } else {
  14. exit('file is not exists');
  15. }