创建文章列表的PHP方法
我计划编写一个函数来动态创建文章和新闻列表,但不知道确切的方法是什么 我有创建文章列表的PHP方法,php,html,arrays,parsing,Php,Html,Arrays,Parsing,我计划编写一个函数来动态创建文章和新闻列表,但不知道确切的方法是什么 我有/articles和/news文件夹,其中包含article1.php,article2.php等文件 这些文件包含变量$date(发布日期),$type(新闻/文章),$h1,
/articles
和/news
文件夹,其中包含article1.php
,article2.php
等文件
这些文件包含变量$date
(发布日期),$type
(新闻/文章),$h1,
(标题,副标题),$short
(短段显示在列表上)
我想创建一个显示在一页上的这些文件的列表
HTML:
- 第二个循环是
newslist.php
或者可能: 二,
- 创建
和articlearray.php
文件,以newsarray.php
key:value=$date:[$type,$h1,$h2,$short]的形式存储来自每篇文章和数组中新闻文件的数据。
- 创建
函数,将整个给定数组解析为HTML(包含所有文件的数据)parsearray
- 在
articlelist.php和
newslist.php中调用
$content=parsearray(…)
- 显示$content
还是有其他更好的解决方案 编辑:
我没有任何数据库,因为文章/新闻数量很少。如果真的有必要的话,我会使用它,但是现在请假设它应该用纯PHP完成。(我问这个问题也是为了学习,不仅仅是为了实用。)首先:建议在不同的文件中管理内容和/或代码(为了更好地理解和维护),但不是强制性的。我会选择以下方法。将内容分为三个文件:
index.php
(包含“main”函数)data.php
(包含数据)functions.php
(包含可调用函数)//functions.php
函数执行($module){
全球美元数据;
$content.='';
foreach($data[$module]作为$item){
$content.=''.$item['date'].';
$content.=''.$item['h1'].';
//$content.=。。。
}
$content.=”;
返回$content;
}
现在,您可以通过index.php?m=articles
或index.php?m=news
调用页面来显示您的文章或新闻
旁注:这种方法使以后切换到数据库变得很容易。您考虑过数据库吗?是的,但我不确定我是否只想将数据库用于此目的。我计划做一个简单的页面,大概有30-40篇文章/新闻。这是我认为效率不高的原因,只是简单的解决办法。谢谢。由于没有人针对我的情况提出更好的解决方案,我可能会接受你的答案,因为这似乎是最好的方法(如果我仍然不使用SQL存储此类数据,我将在未来的项目中使用它)。
<div>
$content <!--here goes list of all articles/news-->
</div>
[pseudocode]
$content = "";
while (get another filename from /articles)
include filename
$content .= (variables from filename.php parsed into html)
display $content
// index.php
require_once 'data.php';
require_once 'functions.php';
$allowedModules = array('articles', 'news');
if(empty($_GET['m']) || null === $_GET['m']) {
die('Module is required');
} else {
$module = $_GET['m'];
}
if(!in_array($module, $allowedModules)) {
die('Invalid module');
}
echo execute($module);
// data.php
$data = array(
'articles' => array(
array(
'date' => '2014-06-10',
'type' => 'article',
'h1' => 'My Headline #1',
'h2' => 'Subheadline #1',
'short' => 'My teaser'
),
array(
'date' => '2014-06-09',
'type' => 'article',
'h1' => 'My Headline #2',
'h2' => 'Subheadline #2',
'short' => 'My teaser'
)
),
'news' => array(
array(
'date' => '2014-06-08',
'type' => 'news',
'h1' => 'My News Headline #3',
'h2' => 'Subheadline #3',
'short' => 'My teaser'
),
)
);
// functions.php
function execute($module) {
global $data;
$content .= '<div>';
foreach($data[$module] as $item) {
$content .= '<span>' . $item['date'] . '</span>';
$content .= '<h1>'. $item['h1'] . '</h1>';
// $content .= ...
}
$content .= "</div>";
return $content;
}