Formatting PHP files which contain primarily (but not solely) HTML

Please consider:

index.php

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

include.php

<?php
	echo '<div class="prcf_header">My included text</div>';
?>

As can be understood from the first code example, I use lots of echo commands there; in practice I need something better than just echoing every line because I normally work with much longer HTML codes.
I thought about using an heredocument, but it will desolate the include command.

How to properly format the first file so I would not need echo commands to output direct HTML, but in such a way that won’t prevent the include command from working?

https://www.php.net/manual/en/function.highlight-file.php

May be useful in in displaying and formatting file contents.

Also a useful constant:

highlight_file( __file__ );

I may be missing the point here (and sorry if I am) but I would write that as:

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

or

<?php
echo"
<!DOCTYPE html>
  <html>
    <body>
";	

include('include.php');

echo "
     </body>
  </html>
";
?>

If the content of the include is simply just HTML, you don’t need the PHP tags or echo, it could simply be pure HTML:-

<div class="prcf_header">My included text</div>

So the include can be used to reduce repetition in the page such as a menu which is identical in all pages, any edit to it only need be done once.
Though if your include contains variables or logic, it can include PHP within it.

<div class="prcf_header">My included text about <?= $textSubject ?></div>

But the best way of doing things depends on the context of what it is you intend to do.

2 Likes

Indeed, in my .php files, eventually I removed all echo commands and their syntax and stayed with just pure HTML and PHP code such as include 'FILE'; just where I needed it and my code works fine this way.

Thank you,

1 Like