1

我想知道如何使用 php 将 html 文档插入另一个文档。例如:

header.html

<div id="header">Hey this is header</div>

index.php

<body>
<? get_document('header.html'); ?>
...

我可以为此使用 ajax,但我不希望我的网站依赖于 js。谢谢!

4

3 回答 3

1

您可以使用include()将一个文档包含在另一个文档中:

<body>
<?php include('header.html'); ?>
...

如果您希望在文件不存在的情况下执行失败,请使用require()

<body>
<?php require('header.html'); ?>
...

请注意,短开标签( <?) 并非在所有服务器上都有效,并且在新版本的 PHP 中默认禁用。为此,最好使用全开标签:<?php

于 2013-06-25T16:30:50.473 回答
1
<html>
...
<body>
<?php
      include("header.html");
?>
</body>
</html>

或者,如果您想将其存储在变量中并稍后根据需要使用

   ob_start();
   include("header.html");
   $content = ob_get_contents();
   ob_end_clean();


   echo $content;
于 2013-06-25T16:36:51.653 回答
0

您可以只使用include/ require。这可以在任何文件上完成,而不仅仅是 PHP 文件。

你也可以这样做echo file_get_contents('header.html');,但include在这种情况下更有意义。

于 2013-06-25T16:30:26.520 回答