服务热线
1888888888
作者:admin发布时间:2023-12-27分类:PHP笔记浏览:268
php教程:如何将完整小说txt文件上传以后按小说章节分割,并将分割后的小说内容按章节内容和章节名写入mysql数据库。然后设计输出章节列表页和章节内容页。
1. 客户端上传小说txt文件到服务器
2. 服务端根据小说的章节规律,将小说按照章节分割成不同的文件,或者将小说存储在内存中进行分割
3. 将章节以及章节内容写入mysql数据库
4. 输出章节列表页和章节内容页
可以使用第三方插件或者原生javascript实现文件上传功能。这里以原生javascript为例:
html提交表单代码:
<form id="upload-form"> <input type="file" name="file" id="file-input"> <button type="submit">上传</button></form><script>document.getElementById('upload-form').addEventListener('submit', function(e) { e.preventDefault(); var fileInput = document.getElementById('file-input'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload.php'); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error(xhr.statusText); } } }; xhr.send(formData);});</script>
服务端根据小说的章节规律,将小说按照章节分割成不同的文件,或者将小说存储在内存中进行分割。这部分需要根据小说的章节规律进行分割,并将分割后的小说章节保存到数据库,下面以将小说保存在内存中进行操作:
<?php$file = $_FILES['file']['tmp_name'];$content = file_get_contents($file);$lines = explode("\n", $content);$chapters = array();$temp = array();foreach ($lines as $line) { $line = trim($line); if (preg_match('/^第\d+章/', $line)) { if (!empty($temp)) { $chapterContent = implode("\n", $temp); $chapters[] = array('title' => $chapterTitle, 'content' => $chapterContent); $temp = array(); } $chapterTitle = $line; } else { $temp[] = $line; }}if (!empty($temp)) { $chapterContent = implode("\n", $temp); $chapters[] = array('title' => $chapterTitle, 'content' => $chapterContent);}// 连接mysql数据库$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";$conn = new mysqli($servername, $username, $password, $dbname);if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);}mysqli_set_charset($conn, 'utf8mb4');// 清空novel表$sql = "TRUNCATE TABLE novel";if ($conn->query($sql) !== TRUE) { echo "Error: " . $sql . "<br>" . $conn->error;}// 循环插入每个章节foreach ($chapters as $chapter) { $title = $chapter['title']; $content = $chapter['content']; $sql = "INSERT INTO novel (title, content) VALUES ('$title', '$content')"; if ($conn->query($sql) !== TRUE) { echo "Error: " . $sql . "<br>" . $conn->error; }}$conn->close();echo '上传成功';?>
第二步的代码已经实现了这个功能。
需要注意的是,输出章节列表和章节内容页需要在前端进行操作,这里使用php输出html以及与mysql进行交互。
章节列表页:
<?php // 连接mysql数据库$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";$conn = new mysqli($servername, $username, $password, $dbname);if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);}// 查询novel表中的所有记录$sql = "SELECT id, title FROM novel";$result = $conn->query($sql);$conn->close();?><!DOCTYPE html><html><head> <meta charset="utf-8"> <title>小说章节列表</title></head><body> <h1>小说章节列表</h1> <?php if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $id = $row["id"]; $title = $row["title"]; echo "<p><a href=\"content.php?id=$id\">$title</a></p>"; } } else { echo "0 结果"; } ?></body></html>
章节内容页:
<?php if (!isset($_GET['id'])) { echo '章节不存在';} else { // 连接mysql数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 查询novel表中指定id的记录 $id = $_GET['id']; $sql = "SELECT title, content FROM novel WHERE id=$id"; $result = $conn->query($sql); $conn->close(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $title = $row["title"]; $content = $row["content"]; echo "<!DOCTYPE html>"; echo "<html>"; echo "<head>"; echo " <meta charset=\"utf-8\">"; echo " <title>$title</title>"; echo "</head>"; echo "<body>"; echo " <h1>$title</h1>"; echo " <p>$content</p>"; echo "</body>"; echo "</html>"; } } else { echo '章节不存在'; }}?>
上面的内容讲了php按章节分割小说txt文件,并存入数据库的教程。教程中特别需要注意的是php对章节内容的判断,可能会要求每章小说内容和标题都要有规律的可识别方法,处理大批量小说txt文件的时候,可能因为小说内容里的章节标志符不明显,而章节分割失败。本文将采用按字数分割TXT小说内容的办法,进行分割。
同时需要创建一个名为 "novel" 的数据库和 "chapters" 表格,可以使用以下代码创建:
CREATE DATABASE novel;USE novel;CREATE TABLE chapters ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(30) NOT NULL, content TEXT NOT NULL);
注意:如果你需要修改表名或者字段名称你在下面的代码中也需要修改。比如你需要加入:小说作者、小说简介、小说分类、阅读统计等常用功能。
文件名称:upload.php
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>上传小说</title></head><body><h1>上传小说</h1><?phpif($_FILES['novel']['error'] > 0){ die('上传失败!');}$filename = $_FILES['novel']['name'];$tmp_name = $_FILES['novel']['tmp_name'];$type = $_FILES['novel']['type'];// 检查文件类型是否为文本文件if($type != 'text/plain'){ die('上传文件类型错误!');}// 读取文件内容$content = file_get_contents($tmp_name);// 按5000字切分内容为章节$chapters = str_split($content, 5000);$chapter_num = count($chapters);// 连接数据库$servername = "localhost";$username = "root";$password = "";$dbname = "novel";$conn = mysqli_connect($servername, $username, $password, $dbname);if (!$conn) { die("连接失败: " . mysqli_connect_error());}// 插入章节到数据库中for($i = 1; $i <= $chapter_num; $i++){ $chapter_content = mysqli_real_escape_string($conn, $chapters[$i-1]); $chapter_title = "第".$i."章"; $sql = "INSERT INTO chapters (title, content) VALUES ('$chapter_title', '$chapter_content')"; if (mysqli_query($conn, $sql)) { echo "章节".$i."上传成功!<br>"; } else { echo "章节".$i."上传失败!<br>"; }}mysqli_close($conn);?><a href="index.php">返回首页</a></body></html>
文件名称:index.php
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>小说阅读</title></head><body><h1>小说阅读</h1><a href="upload-form.php">上传小说</a><hr><?php// 连接数据库$servername = "localhost";$username = "root";$password = "";$dbname = "novel";$conn = mysqli_connect($servername, $username, $password, $dbname);if (!$conn) { die("连接失败: " . mysqli_connect_error());}// 查询章节列表$sql = "SELECT * FROM chapters";$result = mysqli_query($conn, $sql);if (mysqli_num_rows($result) > 0) { // 输出数据 while($row = mysqli_fetch_assoc($result)) { echo "<h2>".$row["title"]."</h2>"; echo "<p>".$row["content"]."</p>"; }} else { echo "暂无章节";}mysqli_close($conn);?></body></html>
文件名称:upload-form.php
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>上传小说</title></head><body> <h1>上传小说</h1> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="novel"> <br> <input type="submit" value="上传"> </form> <a href="index.php">返回首页</a></body></html>
注意:本文只是简单的示例代码,你在实际编写PHP程序的时候还该修改完善PHP代码和美化页面,比如在html中加入需要的css代码和js代码等。
分享:
支付宝
微信