显示列表
 PHP文件操作2011-09-22

1.创建文件
$file = fopen("test.txt","w");
fwrite($file, "Hello World.");
fclose($file);
如果文件已存在,会覆盖内容。

如何生成UTF-8编码的文件?
php是根据文件内容的编码来决定编码的,如果你要自己设定编码,那就用php的编码转换函数(iconv)转换为指定编码再存储
$file = fopen("test.txt","w");
$content = '你好';
$content = iconv('GBK', 'UTF-8', $content);
fwrite($file, $content);
fclose($file);


2.删除文件
$file = "test.txt";
$result = @unlink($file);
if ($result) echo ("OK");
else echo ("Error");
在函数前面加“@”符号,过滤警告提示


3.判断文件是否存在
$file = "test.txt";
if (file_exists($file)) echo ("exist");
else echo ("not exist");


4.创建目录
mkdir("a");
mkdir("a\b\c", 0777, true);这里执行递归创建,会连续创建3个目录,0777是权限


5.删除目录
rmdir("a"); //这样只能删除空的目录


6.判断目录是否存在
is_dir("a"); // 返回1表示存在
is_empty_dir("a"); // 是否为空的目录


7.读取文件
$file = "test.txt";
$content = file_get_contents($file); // 返回字符串
echo $content;


$file = "test.txt";
$content = file($file); // 返回数组,每一行对应一个元素
for($i = 0; $i < count($content); ++$i){
   echo $content[$i]."<br/>";
}

返回摘要 | 分类(PHP) | 访问(0) | 编辑