How would one go about showing PHP code on user end. Sort of like w3School does?
Having lets say a grey area div, and then showing the code in there without activati
You can use html entities <?php
in the html it will be rendered as <?php
You can use htmlspecialchars to encode your code to use html entities.
Typically this is done by showing code within <pre>
or <code>
tags.
The first step is to not wrap that code in PHP tags. So instead of this:
<?
var sample = "code";
?>
You would have this:
var sample = "code";
It's not the code itself which triggers the server-side compile from the PHP engine, it's the tags which indicate to that engine what blocks of the file are code and what are not. Anything that's not code is essentially treated as a string and output to the page as-is for the browser to interpret.
Once you're outputting the code, it's then a matter of formatting it. The old standard is to wrap it in pre
tags to get rid of HTML-ish formatting:
<pre>
var sample = "code";
</pre>
You can also apply CSS style to the pre
tags (or any other tags you want to use for displaying code, such as div
) as you see fit.
There are also very useful code syntax highlighting plugins and tools to make the code a lot "prettier". Google-code-prettify often comes highly recommended.
Simply you can use following code to display php code on webpage.
highlight_string("<?php print('This is php code.'); ?>");
It will give output like
<?php print('This is php code.'); ?>
The PHP code will just be a string that you can echo
or print
onto the page, no different than any other data you want PHP to display for you. If you want to keep the formatting (ex. the indentation), put it inside a <pre><code>
block.
Ex:
$php_code = '<?php $foo = bar; ?>';
echo "<pre><code>$php_code</code></pre>";
Use <pre>
or <code>
tags to wrap your code.
Take a look at http://php.net/manual/en/function.highlight-string.php to further see how you can make the code look pretty.
Since passing a large block of code to highlight_string() can be messy, you may want to look at output buffering in combination with highlight_string to output colorized php code.
Something like:
<?php
ob_start();
?>
phpinfo();
echo "this echo statement isn't executed";
<?php
$code = ob_get_clean();
highlight_string($code);
?>