How to display PHP code on HTML page in browser?

Spread the love

Displaying PHP code on an HTML page involves ensuring the code is not executed by the server but instead shown as plain text in the browser. Here’s how you can do this:

Method 1: Using <pre> and <code> tags

You can wrap your PHP code in HTML <pre> and <code> tags to preserve formatting and display it as plain text:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display PHP Code</title>
</head>
<body>
<h1>PHP Code Example</h1>
<pre><code>
&lt;?php
echo 'Hello, World!';
?&gt;
</code></pre>
</body>
</html>

Method 2: Using HTML Entities

To ensure the PHP code is displayed correctly without being interpreted, you need to convert the special characters to HTML entities:

  • <‘ becomes &lt;
  • >‘ becomes &gt;
  • &‘ becomes &amp;
  • "‘ becomes &quot;
  • '‘ becomes &#039;

Method 3: Using PHP highlight_string() Function

PHP provides a built-in function highlight_string() which can be used to display PHP code with syntax highlighting:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display PHP Code</title>
</head>
<body>
<h1>PHP Code Example</h1>
<?php
$code = '<?php echo "Hello, World!"; ?>';
highlight_string($code);
?>
</body>
</html>

Method 4: Using a Code Block with Backticks (Markdown-style)

If you are using a markdown engine or a system that supports markdown, you can use backticks to display code blocks:

markdownCopy code```php
<?php
echo 'Hello, World!';
?>
```

Method 5: Using JavaScript to Escape HTML

You can also use JavaScript to escape HTML characters dynamically:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display PHP Code</title>
<style>
pre {
background-color: #f4f4f4;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>PHP Code Example</h1>
<pre id="php-code"></pre>
<script>
const phpCode = `<?php
echo 'Hello, World!';
?>`;
document.getElementById('php-code').textContent = phpCode;
</script>
</body>
</html>

These methods ensure that your PHP code is displayed as text in the browser rather than being executed by the server.

Scroll to Top