In web development, HTML defines the structure and content of a page, while PHP handles server-side logic and dynamic functionality. When you want to display real-time data or interact with a backend system, you need to connect HTML and PHP together.
First, create an HTML file (for example, index.html) to define the page layout and static content. Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Example</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
Next, create a PHP file (for example, connect.php) to handle dynamic server-side logic. You can use it to retrieve data or generate dynamic output. Example:
<?php
$name = "John";
?>
To connect HTML and PHP, use PHP code blocks inside your HTML file. The basic syntax looks like this:
<?php
// PHP code goes here
?>
You can embed a PHP file inside an HTML page using the include() function. Example:
<span class="fun"><?php include("connect.php"); ?></span>
This will execute the code from connect.php whenever the HTML file is loaded.
Inside the HTML page, you can use PHP to display variables or other dynamic information. Example:
<span class="fun"><h1><?php echo $name; ?></h1></span>
This code displays the value of the variable $name as an HTML heading.
Save your HTML and PHP files, then place them in your web server’s directory (such as Apache or Nginx). Open the HTML file in a browser, and you’ll see the dynamic PHP content displayed on the page.
By following these steps, you can easily connect HTML and PHP, allowing your website to display interactive and dynamic content seamlessly.