How can PHP code be structured to avoid mixing HTML and PHP, and why is this important for maintainability?

To avoid mixing HTML and PHP, it is important to separate the two languages by using a templating system or MVC architecture. This separation makes the code easier to read, maintain, and debug. By keeping HTML and PHP code separate, it also allows for better collaboration between developers and designers.

<?php
// Example of separating HTML and PHP using a templating system

// Template file (template.php)
<html>
<head>
    <title><?php echo $pageTitle; ?></title>
</head>
<body>
    <h1><?php echo $headerText; ?></h1>
</body>
</html>

// PHP file (index.php)
<?php
$pageTitle = "Home Page";
$headerText = "Welcome to our website!";
include 'template.php';
?>