See the example code at: http://cachecrew.com/sample_code/highlight_file.php and http://cachecrew.com//sample_code/highlight_file2.php.
The PHP and HTML
<div id="php_source" style="display:none"> <!--?<span class="hiddenSpellError" pre=""-->php highlight_file(__FILE__); ?> </div>
<div> wrapper is just a nice structure for allowing you to (CSS) style the content, if you, later, decide. In line 2,
__FILE__ is the path to the source file in which this value is referenced (relative to the code resides on the server, not the URL path).
Show/hide the Source-code
You probably do not want to display the source code by default, so we’ll hide it and provide a place for the user to click to show (or hide) the source code:
<a class="hiddenSpellError" href="#">onClick="document.getElementById( …"></a> <b>Click here to show|hide source</b></a> <div id="php_source" style="display:none"> <!--?<span class="hiddenSpellError" pre=""-->php highlight_file(__FILE__); ?> </div>
First, in line 3, we use the style display:none to hide the source upon initial display. It’d probably be better to put this into a separate style definition.
Next, in line 1, create an
<a> block for the user to click on to show and hide the source. Note that the
href="#" is simply to keep the page from reloading. This can be anywhere, but keeping it just before the source-code to be displayed will keep it in a predictable place and keep it from jumping around as the text is shown and hidden.
We include an
onClick value, above):
document.getElementById('php_source').style.display = document.getElementById('php_source').style.display=='none' ? 'block' : 'none'
Which simply says, “If the display style for the element, php_source, is hidden (i.e., “none”), then display it (set it to “block”), otherwise hide it (set it back to “none”).
Since this is being handled via
onClick, you needn’t use an
<a> tag, you could use any kind of tag; but the
<a> is a simple way to give user-feedback via cursor changes and highlighting.
We want to precede the source code by the selectable tag, so you can make this even more generic by not relying on a hard-coded
id of the
<div> element as follows:
<a href="#" onClick=" … "> <b>Click here to show|hide source</b></a> <div style="display:none"> <!--?<span class="hiddenSpellError" pre=""-->php // The following simply displays the file, presumably PHP source. highlight_file(__FILE__); ?> </div>
onClick code would look like:
this.nextElementSibling.style.display = this.nextElementSibling.style.display=='none' ? 'block' : 'none'
See http://cachecrew.com//sample_code/highlight_file2.php for a working example of this approach.
You can put this at the bottom of your page for other techies to see what you’ve done.