php专区

 首页 > php专区 > PHP高级 > 文件上传 > php读取文件与写入文件方法实例 - php文件操作

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

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

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');  

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');  

实例二,代码如下:

  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($handlefilesize ($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');  
分享到:
php 创建多级目录 - php文件操作
php 创建多级目录 php提供了mkdir来创建文件,但对应5.0一下的版本不支持递归创建多级目录,也就是说给定要创建的目录的上级目录不存在,那么就会创建失败,5.0及以上版本通过吧第三个参数设置为TRUE,就能递归创建指定的目录,不过自己实现一个递归创建多目录的函数也很简单,具体代码如下: f...
PHP判断远程/网络文件是否存在实例总结 -...
PHP判断远程/网络文件是否存在实例总结 如果我们要判断远程文件是否存可以使用很多方法,在php中有ile_get_contents,curl, fsockopen,fopen这些函数都可以获取远程文件. 方法一,代码如下:   方法二,代码如下: //php判断远程文件是否存在  function url_exists($url){  ...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……