美文网首页
PHP将数据写入txt文件

PHP将数据写入txt文件

作者: G加号 | 来源:发表于2021-02-20 11:07 被阅读0次
        // 使用(tp框架为例)
        // 文件就存放在  public/file 目录下
        public function test(){
            $post = json_encode($_POST);
            $this->writeTxt('file',$post);
        }
        /**
         * 写入txt文件,每日按日期生成一个txt文本
         * @param $path 路径(文件名)
         * @param $data 数据(字符串)
         */
        public function writeTxt($path, $data){
            $date = date("Y-m-d", time());
            //项目路径目录,判断是否存在,不存在则创建
            $lujing = "./" . $path;
            if(!is_dir($lujing)){
                mkdir(iconv("UTF-8", "GBK", $lujing),0777,true);
            }
            //文件,判断是否存在,不存在则创建
            $TxtFileName = "./" . $path . "/" . $date . ".txt";
            //以读写方式打写指定文件,如果文件不存则创建
            if(file_exists($TxtFileName))
            {
                //存在,追加写入内容
                file_put_contents($TxtFileName, $data . "\n", FILE_APPEND);
            }
            else
            {
                //不存在,创建并写入
                if( ($TxtRes=fopen ($TxtFileName,"w+")) === FALSE){
                    exit();
                }
                if(!fwrite ($TxtRes,$data. "\n")){ //将信息写入文件
                    fclose($TxtRes);
                    exit();
                }
                fclose ($TxtRes); //关闭指针
            }
        }
    
     
    

    相关文章

      网友评论

          本文标题:PHP将数据写入txt文件

          本文链接:https://www.haomeiwen.com/subject/fkutfltx.html