Dean Elliott
Dean Elliott

Reputation: 189

Output some PHP code into a HTML <code> tag

How can I use the HTML <code> element to output a block of PHP code, without the page running that PHP code? Eg;

<pre><code>
    <?php
        // Some super duper PHP code
    ?>
</code></pre>

I'm creating an API docs page, which features snippets of PHP that anyone wishing to use the API can use as examples, but anything wrapped in <?php> tags runs as an actual PHP function

Upvotes: 0

Views: 1888

Answers (5)

John Fischer III
John Fischer III

Reputation: 11

I had to convert the less-than and greater-than to their HTML name.

<pre><code><?php echo
    "&lt;!--
    This is the church title to be used in the heading of the web-pages.
    Author: John Fischer III of Written For Christ in 2018
    Updated:
    --&gt;
    &lt;?php echo 'Our Little Church:'; ?&gt;" ?>
</code></pre>

Upvotes: 0

Ashfak Md Shibli
Ashfak Md Shibli

Reputation: 305

This may help you.........

######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################

Upvotes: 0

syck
syck

Reputation: 3039

Use &lt;?php and ?&gt;.

The HTML entities will show up as PHP opening and closing tags when the page is rendered, but PHP will obviously not see them. But you have to html-escape your code anyways, otherwise contained HTML-tags will be rendered. So there should be

&lt;?php echo 'Hello, World.&lt;br&gt;'; ?&gt;

Another way would be to have a string specified by a nowdoc and then output html-escaped (demo):

<?php

$code = <<<'EOC'
<?php
echo 'Hello, World.<br>';
// ...your code here...
?>
EOC;

echo htmlentities($code);
?>

Have look for different approaches at How do I display PHP code in HTML?.

Upvotes: 4

iJamesPHP
iJamesPHP

Reputation: 171

Do this via PHP like so:

<?php

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

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

?>

Upvotes: 3

mohsenJsh
mohsenJsh

Reputation: 2108

try something like this:

<?php  echo '<?php'; ?>

Upvotes: 2

Related Questions