user592252
user592252

Reputation:

How do I display PHP code in HTML?

How do I display PHP code in HTML?

Upvotes: 11

Views: 50094

Answers (4)

Álvaro González
Álvaro González

Reputation: 146330

Just like any other piece of text:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
</head>
<body>

<?php

$code = '<?php
echo "Hello, World!";
?>';

echo '<pre>' . htmlspecialchars($code) . '</pre>';

?>

</body>
</html>

Optionally, PHP has a builtin function to generate syntax highlight:

<?php

$code = '<?php
echo "Hello, World!";
?>';

highlight_string($code);

?>

Upvotes: 21

Mark Baker
Mark Baker

Reputation: 212402

highlight_file('myFile.php');

or change the file extension to phps

Upvotes: 18

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use the <pre> tag:

<pre>SOME HTML ENCODED PHP CODE</pre>

Upvotes: -3

phihag
phihag

Reputation: 287755

Replace all occurences of < with &lt; (and optionally > with &gt;):

<pre>
&lt;?php echo 'hello world'; ?&gt;
</pre>

Upvotes: 7

Related Questions