PHP 向文件写入内容

fwrite()

fputs()

file_put_contents()

<?php
    $file = "data.txt";
    $content = "内容标题\r\n内容第一行\r\n内容第二行";

    //打开文件$file时,使用追加模式,此时文件指针会在文件开始出
    if(!$fp = fopen($file,'a'))
    {
        echo "打开文件$file失败!";
        exit;
    }

    if(fwrite($fp,$content) === FALSE)
    {
        echo "写入文件失败!";
        exit;
    }

    echo "写入文件成功!";
    fclose($fp);
    //向当前目录下的data.txt写入一些内容,因为使用了a模式,如果当前目录下不存在data.txt,函数fopen()会尝试创建该文件。
    //fputs是fwrite的别名,用法一样
    //file_put_contents(string $filename,string $data) 相当于依次调用了fopen,fwrite,fclose
?>

猜你喜欢

转载自blog.csdn.net/ferrysoul/article/details/82109192