📜  在 html 中包含外部 php 文件 - PHP (1)

📅  最后修改于: 2023-12-03 15:07:40.225000             🧑  作者: Mango

在 HTML 中包含外部 PHP 文件 - PHP

在开发网站时,我们经常需要在 HTML 文件中嵌入 PHP 代码。然而,有时候我们需要将 PHP 代码分离出来,单独放在一个文件中,以便更好的维护我们的代码。

以下是在 HTML 中包含外部 PHP 文件的步骤:

  1. 创建一个 PHP 文件,将您想要包含在 HTML 文件中的 PHP 代码放在其中。例如,我们创建一个名为 functions.php 的文件,其中包含以下代码:
 <?php
     function helloWorld() {
         echo "Hello, World!";
     }
 ?>
  1. 在您要包含 PHP 代码的 HTML 文件中,添加以下代码:
  <!DOCTYPE html>
  <html>
    <head>
        <meta charset="utf-8">
        <title>My Website</title>
    </head>
    <body>
      <?php include 'functions.php'; ?>
      <h1><?php helloWorld(); ?></h1>
    </body>
  </html>
  1. 在您的 HTML 文件中,添加包含您要引入的 PHP 文件的 include 语句。在上面的例子中,我们使用 include 'functions.php'; 引入了 functions.php 文件。

  2. 最后,我们可以在 HTML 文件的 PHP 代码中使用来自 functions.php 的函数。例如,我们使用 <?php helloWorld(); ?> 来调用 functions.php 中的 helloWorld() 函数,将 "Hello, World!" 输出到 HTML 页面的标题中。

以上就是在 HTML 中包含外部 PHP 文件的基本步骤。您可以使用这个技巧来更好地组织和维护您的代码。