如何在一个php包含文件中包含多个页面内容?

时间:2014-03-02 01:40:36

标签: php html

我想知道如何在一个php文件中包含各种元素(页眉,页脚,导航),而不是创建多个要分别调用的php文件?

在我的包含文件中,我有以下代码:

<?php
echo '<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> Carnival, Residue, Maudlin</span>.</h1>';
?>

输出到运行php的html页面我有:

<?php include('php-includes/current-elements.php');?>

有没有办法包含特定的div或类,而不是整个文件本身?

我只是不想为我想要包含在同一页面上的每个小元素创建一个单独的php包含文件。

以下代码是我在同一个包含文件中调用另一个要在另一个页面上显示的元素的代码。

<?php
function elements ()
{
echo'<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> TESTING</span>.</h1>';
elements();
}
?>

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

听起来你正试图避开模板。基本思想是为每个页眉,页脚,导航定义一个单独的文件,并包含内容模板中的文件。

head.php

<!doctype html> <html> ... 

nav.php

<body> <a href=..> page1 </a> <a href=..> page2 </a> <a href=..> page3 </a>

foot.php

</body> </html>

要创建完整的页面,您可以这样做:

<?php
include 'head.php';
include 'nav.php'

An article about prune juice.

include 'foot.php';
?>

现在,如果我理解正确,你想只包含一个文件,并能够生成各种元素(head,nav,whathaveyou)。您可以通过在函数中包装include语句来完成此操作:

ubertemplate

<?php
function head() { include 'head.php'; }
function nav() { include 'nav.php'; }

function randomElement() { ?>
    An article about prune juice. <?php
}

function totalymisguideddynamiccontents() {
    echo "<div> foobar <span> moo </span></div>"
}

function() { include 'foot.php'; }
?>

..然后在最后一页中,调用这些函数:

uberpage

<?php

include 'ubertemplate.php';
?>    

<?php head() ?>
<script src=superlib.js></src>
<?php nav() ?>

Yomama so big when she wears a yellow coat people yell TAXI!. 

<?php foot() ?>

最后,如果我理解正确并且你认为uberpage方法似乎是一个好主意,那么你应该尝试一下。这可能是认识到它存在缺陷的唯一途径。我不是故意嘲笑你的想法,但有更好的方法来处理模板,第一种方式,你试图避免的,更清洁(但这只是我的意见)。

为了更好的方式,请查看树枝模板或进行更多研究,找到适合您需求的框架。

相关问题