创建文章列表的PHP方法


PHP approach to creating article list

我打算写一个函数来动态创建文章和新闻列表,但是不知道确切的方法是什么

我有/articles/news文件夹包含像article1.php, article2.php等文件。

这些文件包含变量$date(发布日期),$type(新闻/文章),$h1, $h2(标题,副标题),$short(短段落显示在列表中)。

我想创建这些文件的列表显示在一个页面上。

HTML:

<div>
    $content <!--here goes list of all articles/news-->
</div>


这样是不是更好:


1 .

  • articlelist.php中写入while循环:
<>之前(伪代码)$content = ";While(从/articles中获取另一个文件名)包括文件名$content .=(将filename.php中的变量解析为html)显示美元的内容之前
  • newslist.php也是同样的循环。

(使用这种方法,例如按日期排序文章可能很困难。)



或者:

2。

  • 创建articlearray.phpnewsarray.php文件,以数组形式存储每篇文章和新闻文件中的数据,格式为key : value = $date : [$type, $h1, $h2, $short]
  • 创建parsearray函数解析整个给定数组到HTML(包含来自所有文件的数据)
  • 呼叫articlelist.phpnewslist.php中的$content = parsearray(...)
  • 显示美元内容。



或者有其他更好的解决方案吗?

编辑:

我没有任何数据库,因为文章/新闻实在太少了。如果真的有必要,我将使用一个,但目前请假设它应该用纯PHP完成。(我问这个问题也是为了学习,而不仅仅是实用。)

首先:建议在不同的文件中管理您的内容和代码(为了更好的可理解性和可维护性),但不是强制性的。我会选择以下方法。把你的内容分成三个文件:

  1. index.php(包含"主要"功能)
  2. data.php(含数据)
  3. functions.php(包含可调用函数)
<标题> index . php h1> data.php h1> 显然也
// 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;
}

现在您可以通过index.php?m=articlesindex.php?m=news调用您的页面来显示您的文章或新闻。

旁注:这种方法使以后切换到数据库更容易。