如何重用 html 作为页脚


How to reuse html for footer

我看到关于创建 php 文件以重用页眉/页脚的多个答案,但没有足够具体的东西。 我似乎无法让它工作。

php文件到底是什么样子的

,我的html文件到底是什么样子的(给定下面的代码(? 我是否必须将所有 html 文件转换为 php 文件才能使用 php 包含行?

<div id="footer2-wrap">  
    <div class="container">  
        <table id="header">  
            <tr>  
                <td class="phone-number"><span class='wsite-text wsite-phone'>Copyright 2015 | xxx Corporation</span></td>
            </tr>
                    </table>
    </div>

使用页脚数据创建新文件。让我们给它起个名字:footer.php

<div id="footer2-wrap">  
    <div class="container">copyright etc...</div>
<div>

然后在主模板(或索引.php文件中,包含页脚文件:

include_once('footer.php');

你应该在 PHP 中使用 include((、require(( 或 require_once 函数来包含你的文件,这取决于你的情况。

例如,假设您有一个基本的php文件,称为index.php并且您想要添加侧边栏.php,页脚.php,导航.php。

索引.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
    <?php 
    include("sidebar.php");
    include("navigation.php");
    include("footer.php"); // we include footer.php here. you can use .html extension, too.
    ?>
</body>
</html>

页脚.php(或 HTML(

<a href="">About us</a>
<a href="">Our work</a>
<a href="">Testimonials</a>
<a href="">What we do</a>
<a href="">Contact us</a>

是的,您必须有一个.php文件才能使用 PHP,您的服务器也必须安装 PHP(但大多数已经安装了(。PHP 还会增加页面的加载时间,因此在使用它时要考虑到这一点。要使用 PHP 添加页脚,您可以使用 PHP 函数 include() ,或者,我不确定这是否被认为是正确的,file-get-contents()

include()

<?php 
    include("footer.html");
?>

file-get-contents()

<?php
$footer = file_get_contents('footer.html');
echo $footer;
?>

你也可以用 JavaScript 做同样的事情:

var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
document.getElementById("footer").innerHTML=text;

代码取自此处。

注: 该文件必须位于同一域中才能使用 JS。

首先创建一个名为menu.php的文件(如果你使用.html它不起作用(在该 php 文件上为您的菜单编写 html 代码

<div id="navbar">
more code
</div>

At your main html file write 
<?php 
    include("menu.php");
?>

代码应该能够运行。确保通过 Apache 运行代码。下载 Xammp 或 wammp。启动 Apache,将您的项目文件夹复制粘贴到 httdocs 下的 xammp 文件夹中。然后在浏览器上键入localhost/[your project name]并确保html文件更改为 .php

如果你想将参数传递给它,你可以这样做:

file1.php

echo $my_var;

file2.php

$my_var="hello world";
include_once('file1.php');