在php中读取文件我们需要使用file_get_contents或fopen来打开文件然后再读取了,file_get_contents函数读文件比fopen要方便,写文件需要fopen函数与file_put_contents或fwrite合作才可以实例下面我来介绍下.
php写文件的方法
实例一,代码如下:
- $filename = 'test.txt';
- $filename = dirname ( __FILE__ ) . '/' . $filename;
- if (file_exists ( $filename )) {
- if (! is_writable ( $filename )) {
- exit('is not writable');
- }
- $handle = fopen ( $filename, "a+b" );
- $content = 'this is test words';
- $content .= "n";
- fwrite($handle, $content);
- fclose ( $handle );
- } else {
- exit('file is not exists');
- }
实例二,代码如下:
- $filename = 'test.txt';
- $filename = dirname ( __FILE__ ) . '/' . $filename;
- if (file_exists ( $filename )) {
- if (! is_writable ( $filename )) {
- exit('is not writable');
- }
- $content = 'this is test words';
- $content .= "n";
- file_put_contents($filename, utf8_encode($content));
- } else {
- exit('file is not exists');
- }
php读取文件
实例一,代码如下:
- $filename = 'test.txt';
- $filename = dirname ( __FILE__ ) . '/' . $filename;
- if (file_exists ( $filename )) {
- if (! is_readable ( $filename )) {
- exit('is not readable');
- }
- $contents = file_get_contents($filename);
- $contents = explode("n", $contents);
- print_r($contents);
- } else {
- exit('file is not exists');
- }
实例二,代码如下:
- $filename = 'test.txt';
- $filename = dirname ( __FILE__ ) . '/' . $filename;
- if (file_exists ( $filename )) {
- if (! is_readable ( $filename )) {
- exit('is not readable');
- }
- $handle = fopen ( $filename, "rb" );
- $contents = fread($handle, filesize ($filename));
-
- $contents = explode("n", $contents);
- fclose ( $handle );
- print_r($contents);
- } else {
- exit('file is not exists');
- }
|