PHP 文件创建 写入

在php中,没有一个专门的函数创建文件。他是通过fopen 函数来实现

function fopen($filename,$mode);

$mode取值

举例说明 第一种: $model = 'w';

$fwirte($fp,$conn)  第三个参数不写 默认写完 ;

\r\d 中 只有双引号才转义  单引号不转义

<?php
header("content-type:text/html;charset=utf-8");

$file_full_path = 'F:/hello.txt';
if(!file_exists($file_full_path)){

    if($fp=fopen($file_full_path,'w')){
        $conn = '';
        for($t=0;$t<10;$t++){
            $conn = $conn."hello world\r\n";
        }
        //int fwrite ( resource handle, string string [, int length] )
        // fwrite() 把 string 的内容写入 文件指针 handle 处。 如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止,视乎先碰到哪种情况。 
        // fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。 
        fwrite($fp,$conn);
        fclose($fp);
    }else{
        echo "<br>创建失败 ";
    }

}else{
    echo '<br> 文件已经存在';
}

第二种案例 : 

 将已有的文件 的内容改为 你好 张三;

<?php
header("content-type:text/html;charset=utf-8");

$file_full_path = 'F:hello.txt';
if(file_exists($file_full_path)){

    if($fp=fopen($file_full_path,'w')){
        $conn = '';
        for($t=0;$t<10;$t++){
            $conn = $conn."你好PHP\r\n";
        }
        echo $conn;
        //int fwrite ( resource handle, string string [, int length] )
        // fwrite() 把 string 的内容写入 文件指针 handle 处。 如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止,视乎先碰到哪种情况。 
        // fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。 
        fwrite($fp,$conn);
        fclose($fp);
    }else{
        echo "<br>创建失败 ";
    }

}else{
    echo '<br> 文件不存在,无法覆盖';
}

猜你喜欢

转载自blog.csdn.net/yhwcool/article/details/81981356