PHP让内容动起来
上一节最后写文章,然后点“发表”,结果文章怎么不见了?
因为那是静态HTML网页,不能处理数据。这时候就需要开发PHP程序了。
修改“发表页”create_article.html
的form(表单)的action属性值,改成./store_article.php
。代码如下:
<h1>写文章</h1>
<form action="./store_article.php" method="post">
./
表示本目录,所以需要到网站根目录里创建store_article.php
,它收到表单提交的数据后,保存到哪里呢?最简单的方法:本地文件。代码如下:
<?php
$input = $_POST;
$file = './articles.json';
$data = [];
if (file_exists($file)) {
$tmp = file_get_contents($file); //读取文件,变成字符串
if(!empty($tmp)) {
$data = json_decode($tmp, true); //json解码成array
}
}
$data[] = $input;
file_put_contents($file, json_encode($data)); //把字符串保存到文件
echo '发表成功';
能看懂这些代码吗?如果看不懂,自学一下PHP语法,很简单(预计需要0.5天)。推荐教材:《PHP官方手册:第一个 PHP 页面》php.net/manual/zh/tutorial.firstpage.php
然后创建一个index.php
作为首页,用来读取所有文章,并显示一段摘要,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cmn-Hans" lang="cmn-Hans">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>在线阅读网</title>
</head>
<body>
<h1>在线阅读网</h1>
<div><a href="./create_article.html">写文章</a></div>
<?php
$file = './articles.json';
if (file_exists($file)) {
$tmp = file_get_contents($file);
if (!empty($tmp)) {
echo '<ul>';
$data = json_decode($tmp, true);
foreach($data as $k=>$v) {
$id = $k + 1;
echo '<li><a href="./show_article.php?id=' . $id . '">' . $v['title'] . '</a>';
echo '<p>' . mb_substr($v['content'], 0, 200, 'UTF-8') . '</p></li>';
}
echo '</ul>';
}
}
?>
</body>
</html>
再创建一个show_article.php
作为详情页,去显示单独的一篇文章,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cmn-Hans" lang="cmn-Hans">
<?php
$input = $_GET;
$id = $input['id'];
$file = './articles.json';
if (file_exists($file)) {
$tmp = file_get_contents($file);
if (!empty($tmp)) {
$articles = json_decode($tmp, true);
$article = $articles[$id-1];
}
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?=$article['title']?> - 在线阅读网</title>
</head>
<body>
<div><a href="./">回首页</a></div>
<h1><?=$article['title']?></h1>
<div>作者:<?=$article['author']?></div>
<div><?=nl2br($article['content'])?>
</div>
</body>
</html>
本节代码下载:github.com/sinkcup/phbook/tree/0.2
开发完毕,在浏览器里访问,尝试录入一篇文章。如图:
写文章
发表成功,但右上角提示:HTML语法错误
发表成功,但出现乱码
然后回到首页,刷新,看到文章列表,可以点进去阅读,如图:
首页:能看到文章列表
详情页
总结一下
我的技术水平
HTML | 服务器部署 | PHP | 数据存储 | HTTP协议 |
---|---|---|---|---|
HTML标准和语义化 | 安装WAMP/LAMP | 让内容动起来 | json文件存数据 | GET、POST |
作业
- 了解HTTP协议:GET和POST有什么区别?该用哪个?
- 扩展阅读:《JSON数据格式》
- 扩展阅读:《阿里 IPO 后员工套现 410 亿美元,对杭州这个城市会有怎样的影响? - 知乎》
待解决的问题
-
PHP和HTML混写,很乱啊,怎么解决?
且听下回分解。
-
保存之后,在页面怎么出现HTML语法错误甚至乱码了?
且听下回分解。