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.
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.
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>= 'Hello, PHP!' ?></p> </body> </html>
This method omits the echo statement, making the code cleaner and easier to read.
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.