PHP将数据写入txt文件

PHP将数据写入txt文件,第1张

//记录返回值

        $write_data_a = [

            'html_url'  =>  $getUrl,

            'ip'    =>$this->get_real_ip(),

            'time'  =>  date("Y-m-d H:i:s",time()),

            'res'   =>$response

        ]

//转化为JSON

        $write_data_a = json_encode($write_data_a) . '||' . "\n"

        $date = date("Y-m-d", time())

//项目路径目录,判断是否存在不存在则创建

        $lujing = "./360_mobile_res_sd"

        if(!is_dir($lujing)){

            mkdir(iconv("UTF-8", "GBK", $lujing),0777,true)

        }

//文件,判断是否存在,不存在则创建

        $TxtFileName = "./360_mobile_res_sd/" . $date . "_2.txt"

        //以读写方式打写指定文件,如果文件不存则创建

        if(file_exists($TxtFileName))

        {

//存在,追加写入内容

            file_put_contents($TxtFileName, $write_data_a, FILE_APPEND)

        }

        else

        {

//不存在,创建并写入

            if( ($TxtRes=fopen ($TxtFileName,"w+")) === FALSE){

                exit()

            }

            if(!fwrite ($TxtRes,$write_data_a)){ //将信息写入文件

                fclose($TxtRes)

                exit()

            }

            fclose ($TxtRes)//关闭指针

        }

使用form表单post数据到PHP,然后用file_put_contents($fileName, $data)写入文件,$fileName是文件名,$data是要写入的数据

新建一个a.php文件,将下面的复制进去访问一下,填写后点击提交,会生成一个a.txt的文件,里面是你填写的内容

可能会有一个notice的报错,不必理会

<?php

$data = $_POST['text']

$fileName = 'a.txt'

file_put_contents($fileName, $data)

?>

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>test</title>

</head>

<body>

<form action="./a.php" method="post">

<textarea name="text" id="" cols="30" rows="10"></textarea>

<input type="submit" value="提交">

</form>

</body>

</html>

错误太多了

主要是 $fil="myDirl/name.txt"

myDirl不存在的话, fwrite不能新建文件又新建文件夹

还有,这个$fil是要相对于程序文件的相对路径

如非windows,还得注意读写权限

麻烦!

这样简单

<?php

file_put_contents ( 'xxx.txt', '要写入内容' )

?>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/12046946.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-20
下一篇2023-05-20

发表评论

登录后才能评论

评论列表(0条)

    保存