Home >Backend Development >PHP Tutorial >Code example for TP5 to read txt file

Code example for TP5 to read txt file

不言
不言forward
2019-03-29 10:37:115606browse

The content of this article is about the code example of TP5 reading txt files. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Read the file

Put the txt file into the public folder. (This is the data format in my TXT)
    324654658654
    FASDREWRQERWE
    FASBDSRFEWRQE
    ASDFERQWEFSDF
    ERQGHDSFSWERQE
    ASDFERQEWFASQ
    RQWERQWEDADSE
TP5 has a built-in class File for processing files. It inherits SplFileObject, so you can use all the properties and methods in SplFileObject
    use think\File;
    $file = file_get_contents('data1.txt'); //获取出来是字符串类型

2. String to array

        PHP 中 \r\n 代表空格回车
       $rep = str_replace("\r\n", ',', $file); //将字符中所有的 回车空格转替换成 ,
       //explode将字符串根据某个字符转成数组
       //explode 中不能为正则,也不能为空串 
       $cont = explode(',', $rep);

Code display in the project

    <?php
    namespace app\index\controller;
    use think\Controller;
    use think\Db;
    use think\File;
    class Active extends Controller
    {
        //读取TXT文件内容 
        public function read(){
            $file = file_get_contents(&#39;data1.txt&#39;); 
            $rep = str_replace("\r\n", &#39;,&#39;, $file); 
            $cont = explode(&#39;,&#39;, $rep);
           for($i=0;$i<count($cont);$i++){
               $data = [
                   &#39;code&#39; => $cont[$i],
                   'status' => 0,
                   'time' => time()
               ];
               $inser = Db::name('active')->insert($data);
               if($inser){
                   echo 'done';
               }else{
                    echo 'fail';
               }
           }
           
        }
    }

This article has ended here. For more other exciting content, you can pay attention to the of the PHP Chinese website PHP video tutorial column!

The above is the detailed content of Code example for TP5 to read txt file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete