五,写入文件

php向文件中写入内容和读取类似,用fwrite()代替fread()。

php向文件中写入内容有两种方式:

(1)第一种方式

/*第一种写入文件方式*/
$file_path = "test.txt";
if(file_exists($file_path)){
    $fp = fopen($file_path,'a+');
    $str = '你好
';
    for($i = 0; $i < 10; $i++){
        fwrite($fp,$str);
    }
    fclose($fp);
    echo '写入成功!';
}else{
    echo '文件不存在!';
}

  (2)第二种方式

/*第二种写入文件方式*/
$file_path = "test.txt";
$str = "北京你好
";
file_put_contents($file_path,$str);
//默认是覆盖,file_put-contents(Sfile_path,$str,FILE_APPEND)这样是在原内容基础上追加字符串

  

原文地址:https://www.cnblogs.com/usa007lhy/p/5731163.html