文件内容写入及读取

原创2019-10-07 14:17:5812
摘要:<!DOCTYPE html> <html>         <head>                 <

<!DOCTYPE html>

<html>

         <head>

                 <title>create 'txt' file</title>

                 <style type="text/css">

                 *{margin:0;padding: 0;}

                 div{margin: 30px auto;width: 400px;}

                 input{margin: 0 10px;}

                 textarea{width: 400px;height:200px; resize: none;}

                 </style>

         </head>

<body>

                 <div>

                         <form action="samFile.php" method="post">

                                  <p>请输入文件名:<input type="text" name="fileName"></p>

                                  <p>请输入文件内容:</p>

                                  <p> <textarea name="content"></textarea> </p>

                                  <input type="submit" name="submit">

                         </form>

                 </div>

            <hr>

             <div>

                         <p class="fileName"></p>

                         <p class="fileContent"></p>

             </div>

</body>

             <script>

                 var fileName=document.getElementsByClassName('fileName').item(0);

                 var fileContent= document.getElementsByClassName('fileContent').item(0);

            </script>

             <?php

                     //获取请求的文件名

                     @$fileName = $_REQUEST['fileName'];

                     //获取文件内容

                     @$content = $_REQUEST['content'];

                     //未填文件名,不操作

                     if(!empty($fileName)){

                              //为文件名加入反缀名

                             $fileName=$fileName.'.txt';

                             //创建一个文本文件

                             if(!file_exists($fileName)){

                                             touch($fileName);

                              }

                             //打开文本文件回一个资源

                          $file = fopen($fileName,'a+');

                           //写入内容

                         fwrite($file,$content."\r\n");

                          //声明一个空数组,存入字符串

                          $fileStr=[];

                          //文件指针到开头

                          rewind($file);

                          //读取文件内容到数组

                         while (!feof($file)) {

                                  //$fileStr[] = fgets($file);

                                 $fileStr[]=fgets($file);

                           }

                         //数组转字符串变量

                          $str=implode($fileStr);

                         //去掉字符串的换行符

                         $str = preg_replace('/\n|\r\n/','<br>',$str);

                          //内容显示到页面上

                          echo "<script>fileName.innerHTML='文件名为: {$fileName}';fileContent.innerHTML='{$str}';</script>";

             }

             ?>

</html>


批改老师:Peter-Zhu批改时间:2019-10-12 16:29:02
老师总结:OK, 赶紧学习剩下 的课程吧, 加油

发布手记

热门词条

第九期线上培训班