php 拆分txt小说章节保存到数据库

本文介绍了一种使用PHP从TXT文件中解析小说章节标题和内容的方法,并将其存储为数组以便进一步处理或存入数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$xs_capter_list = [];
            $xs_content_list = [];
            set_time_limit(0);//0表示不限时

            $file = fopen('txt小说地址', "r");
            $i = 0;//行数
            $j = 1; //章节数
            $content = '';
            $chaptertitle ='';
            //输出文本中所有的行,直到文件结束为止。
            while(true) {
                if(feof($file)){
                    //文章结尾
                    if($content!='' && $chaptertitle!=''){
                        $content = strtr($content,["\r\n" => '<br>']);
                        $content = mb_substr($content,49);//去掉前49个广告字符
                        $xs_content_list[] = $content;
                        //成功后
                        break;
                    }
                    break;
                }else{
                    $now = fgets($file);
                    $now = mb_convert_encoding($now,'UTF-8','UTF-8,GBK,GB2312,BIG5');//使用该函数对结果进行转码
                    //var_dump($now);
                        if(strpos($now,'第')!==FALSE and strpos($now,'章')!==FALSE){
                            //判断上一层循环
                            if($content!='' && $chaptertitle!=''){
                                //执行插入操作
                                $content = strtr($content,["\r\n" => '<br>']);
                                $content = mb_substr($content,49);//去掉前49个广告字符
                                $xs_content_list[] = $content;
                                //成功后
                                $content = '';
                                $chaptertitle = strtr($now,["\r\n" => '']);
                                //var_dump($chaptertitle);
                                $j++;
                            }else{
                                $content .= $now;
                                $chaptertitle = strtr($now,["\r\n" => '']);
                            }

                            $xs_capter_list[] = $chaptertitle;
                            //die();


                        }else{
                            $content .= $now;
                        }

                }

                $i++;
            }

            foreach($xs_capter_list as $key=>$v){
                $chapter['content'] = $xs_content_list[$key];
                $chapter['total'] = mb_strlen($xs_content_list[$key]);;

                $chapter_id = $this->sql('xs.nh_chapter')->insertId($chapter);

            }

临时写的代码,比较乱,还有待于优化。

思路是一行一行的读取txt文本,利用小说 “第三章 桌下的手”  这种类似的关键字来分拆章节

最后生成两个数组 

$xs_capter_list和
$xs_content_list 来分别保存标题和内容,然后写入数据库

转载于:https://www.cnblogs.com/tingfengqieyu/p/8631257.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值