Current Location: Home> Latest Articles> Detailed Guide to Embedding PHP in HTML with Examples

Detailed Guide to Embedding PHP in HTML with Examples

M66 2025-09-30

Directly Embedding PHP in HTML

Direct embedding is the most common method, where PHP code is written directly in an HTML file using <?php ?> tags. For example:

<!DOCTYPE html>
<html>
<head>
    <title>Direct PHP Embedding Example</title>
</head>
<body>
    <h1>Direct PHP Embedding Example</h1>
    <?php
    // PHP code block
    $name = 'Alice';
    echo 'Hello, ' . $name . '!';
    ?>
</body>
</html>

This example outputs "Hello, Alice!" directly within the HTML file.

Embedding PHP via Included Files

Another method is to include external PHP files, which makes the code easier to maintain and reuse. Example:

<?php
// greeting.php
$name = 'Bob';
echo 'Hello, ' . $name . '!';
?>

In an HTML file, include this file using include or require:

<!DOCTYPE html>
<html>
<head>
    <title>Include File Example</title>
</head>
<body>
    <h1>Include File Example</h1>
    <?php include 'greeting.php'; ?>
</body>
</html>

This outputs "Hello, Bob!", demonstrating code reuse.

Using PHP Short Tags

Besides direct embedding and including files, you can use PHP short tags to quickly output content:

<!DOCTYPE html>
<html>
<head>
    <title>PHP Short Tag Example</title>
</head>
<body>
    <h1>PHP Short Tag Example</h1>
    <p></p>
</body>
</html>

This method omits the echo statement, making the code cleaner and easier to read.

Conclusion

This article demonstrated three ways to embed PHP in HTML: direct embedding, including files, and using short tags. Mastering these methods can improve web development efficiency and enhance code maintainability and reusability.