How can default values be inserted into HTML form elements using PHP variables without causing header modification issues?

When inserting default values into HTML form elements using PHP variables, it's important to ensure that the PHP code is placed before any HTML output to avoid header modification issues. One way to do this is by using PHP to echo the default values directly into the form elements within the HTML code.

<?php
// Define default values
$default_name = "John Doe";
$default_email = "johndoe@example.com";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['name'];
    $email = $_POST['email'];
} else {
    // Set default values
    $name = $default_name;
    $email = $default_email;
}
?>

<form method="post" action="">
    <input type="text" name="name" value="<?php echo $name; ?>">
    <input type="email" name="email" value="<?php echo $email; ?>">
    <button type="submit">Submit</button>
</form>