How to write PHP code in HTML
In PHP, you can embed code directly within HTML files by using special tags. The most common way to include PHP code in HTML is by using the opening <?php
tag and the closing ?>
tag.
Here's a basic example:
<!DOCTYPE html>
<html>
<head>
<title>PHP in HTML Example</title>
</head>
<body>
<h1><?php echo "Hello, World!"; ?></h1>
<?php
// Some PHP code here
$variable = "This is a PHP variable.";
echo "<p>$variable</p>";
?>
</body>
</html>
In this example:
<?php
is the opening tag that signifies the beginning of a PHP code block.?>
is the closing tag that signifies the end of a PHP code block.
Everything between these tags is treated as PHP code and will be executed on the server before the HTML is sent to the client's browser.
You can include PHP code anywhere within your HTML document, whether it's inside the <head>
section, the <body>
section, or even within attributes of HTML tags.
Here's another example showing PHP code within an attribute:
<!DOCTYPE html>
<html>
<head>
<title>PHP in HTML Attribute Example</title>
</head>
<body>
<a href="<?php echo "https://www.example.com"; ?>">
Visit Example.com</a>
</body>
</html>
In this example, the href
attribute of the <a>
(anchor) tag includes PHP code to dynamically generate the link.
Remember that for this to work, your server must be configured to recognize and process PHP files. The file should have a ".php" extension for the server to treat it as a PHP script. If you are working on a local server or using a hosting service, this is often configured by default.
Thank you.