PHP-in-HTML with HTML-in-PHP combo fails

I am trying to combine PHP-in-HTML with HTML-in-PHP as a test.

HTML file:

<!DOCTYPE html>
<html>
    <body>
        <?php
            include 'test.php';
        ?>
    </body>
</html>

PHP file

<?php
    echo "<p>test</p>";
?>

Sadly it doesn’t work, the included echoed HTML as <p>test</p> wasn’t included in the HTML file (which I execute on a local XAMPP all-default environment on Windows 10).

There is no error in the browser — the HTML file just appears empty (i.e. no inclusion occurs).

What might be the problem?

Do your files have a .php extension?

2 Likes

The file with HTML doesn’t but the file with PHP does.
I assumed that PHP is automatically recognized in HTML files because I just looked at code examples and due to the vast popularity of the language in web development, I understand I was wrong and both need to have php extensions.

1 Like

If you are just starting out with PHP I recommend the following validation functions which will throw errors rather than hide warnings etc:

<?php  declare(strict_types=1); // applies to this file only
error_reporting(-1); // logs errors and warnings

// following should already be set in php.ini 
// and removed when ONLINE to prevent display of sensitive data
ini_set('display_errors', 'true');


?><!DOCTYPE html>
<html>
    <body>
        <?php
            // store all include files in a common directory
            // underscore prefix denotes include file
            include 'incs/_test.php'; 
        ?>
    </body>
</html>


1 Like

The HTML file should have a .php extension too. That way it will parse the PHP when the <?php tags are encountered anywhere in the document…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.