我需要帮助。在我的网站上,我使用URL参数来决定在页面上包括哪些其他PHP文件。我的第一个问题是:什么应该在index.php中,什么应该在包含的php文件中?
在互联网上,我找到了一些说明,建议使用index.php:的结构
<html>
<head>
<?php include 'header.php'; ?>
</head>
<body>
<?php include 'menu.php'; ?>
<?php include 'content.php'; /* Including page based on the parameters in the url */ ?>
</body>
</html>
使用这种结构,如何根据content.php
中的内容更改<head>
部分中的数据?例如,对于index.php?option=article&id_article=1
,我将包括article.php
,并显示id为1的文章。那么,在包含文章之前编写<head>
时,我如何更改<title>
、<meta
>等内容?
谢谢!
一个有点难看但会起作用的选项是,不要让header.php echo
让它简单地设置$title
和$meta[]
等变量。此外,没有让article.php从回显返回一个类似$html
的变量。同样在article.php中,你可以覆盖header.php中设置的任何变量。然后你可以像这样构建你的index.php:
<?php include 'header.php'; ?>
<?php include 'article.php'; ?>
<html>
<head>
<?php echo $title ?>
</ head>
<body>
<?php include 'menu.php'; ?>
<?php echo $html ?>
</ body>
</ html>
或者您可以查看ob_start()
和ob_flush()
等…
为了尽可能简单,您可以将头设为函数,然后在其他地方调用该函数。。。
示例(未经测试):
function drawHeader($title, $desc = "", $keywords = "", $extra = "") {
?>
<head>
<title><?php echo $title; ?></title>
<meta name="description" content="<?php echo $desc; ?>">
<meta name="keywords" content="<?php echo $keywords; ?>">
<link rel="stylesheet" type="text/css" href="path/to/my.css">
<?php echo $extra; ?>
</head>
<?php
}
上面的目标是让你可以轻松快速地做一些事情,比如。。。
<!DOCTYPE html>
<html>
<?php drawHeader("Home", "Some description", "Some, keywords, here"); ?>
<body>
<h1>Hello, world</h1>
<?php drawFooter(); // maybe a footer of some type? ?>
</body>
</html>
或者,您可以在调用包含的文件之前设置变量。。。并且在所包含的文件中只是在适当的位置回显那些值。
有很多方法可以做到这一点,有很多标准和最佳实践、框架、模板系统、使用输出缓冲的占位符等。
首先,您发现的指令没有什么可从中学习的
作为第二个获取文件article.php 的内容
使用url index.php?option=article&id_article=1
您需要使用$_GET['id_article']
示例:
$page = $_GET {'id_article'};
if (isset($page)) {
$url = $page.".php";
if (file_exists($url)) {
include $url;
}
你可以使用数据库来存储文章,然后使用进行查询
if ($_REQUEST['id_article'] == $page) {
$querythearticle = mysql_query("select tablename from database_name where id_article='$page'");
}