将一些PHP代码输出到HTML <code> tag

时间:2016-03-04 17:46:50

标签: php html special-characters

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

5 个答案:

答案 0 :(得分:4)

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?.

答案 1 :(得分:3)

Do this via PHP like so:

<?php

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

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

?>

答案 2 :(得分:2)

try something like this:

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

答案 3 :(得分:0)

这可能对你有帮助.........

######################################################################
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>";
#######################################################################

答案 4 :(得分:0)

我必须将less-than和greater-than转换为HTML名称。

<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>