You can do it in at least three ways.
Form 1: From PHP code
You write the entire code snippet in a string by storing it in a variable. But you need to make a change in the way you use the quotes: at the beginning and at the end of the string you should use single quotes '
and in the variables double quotation marks "
, otherwise, the variables will be interpreted as such and it's not what's interesting here.
Then print that string using highlight_string
. It is a PHP function that does the following according to the Manual:
Print or return html marks for a version with the syntax
highlighted the given PHP code using the colors defined in the
PHP internal syntax highlighter.
That way it will show you the indented code and (according to the Manual, with colors, according to the PHP color configuration).
This would be the code:
$strCode='
if(isset($_POST["btn_grabar"]))
$id_hipodromo = $_SESSION["id_"];
$id_animal=$_POST["id_animal"];
$nombre=$_POST["nombre"];';
echo highlight_string($strCode);
Result on screen:
if(isset($_POST["btn_grabar"]))
$id_hipodromo = $_SESSION["id_"];
$id_animal=$_POST["id_animal"];
$nombre=$_POST["nombre"];
Form 2: Mix of PHP and HTML
You open an HTML block in your PHP and show the code. In this case, since you are in HTML, you can leave the single quotes as you originally had, since you are in HTML and the variables will not be interpreted as PHP variables.
<?php
//Código PHP
?>
<html>
<body>
<code>
if(isset($_POST['btn_grabar'])) <br />
$id_hipodromo = $_SESSION['id_']; <br />
$id_animal=$_POST['id_animal']; <br />
$nombre=$_POST['nombre']; <br />
</code>
</body>
</html>
Result on screen:
if(isset($_POST['btn_grabar']))
$id_hipodromo = $_SESSION['id_'];
$id_animal=$_POST['id_animal'];
$nombre=$_POST['nombre'];
Here the problem is that the code is not indented.
Form 3: with an external library
You can use a library to display embedded code with colors, for example Google Code Prettify . This is the way that sites that work with code examples usually use.
You just have to add the library (JS), like any other:
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
And then open a tag like this:
<pre class="prettyprint lang-php">
Here you indicate that you want the PHP syntax using lang-php
, for the code color.
Then you write inside the code properly indented and in the end you close the label </pre>
.
Let's see a test. Here we are in HTML, it can be done in PHP, adding to the chain what is necessary. Click on Ejecutar
, to see the result.
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
<pre class="prettyprint lang-php">
if(isset($_POST['btn_grabar']))
$id_hipodromo = $_SESSION['id_'];
$id_animal=$_POST['id_animal'];
$nombre=$_POST['nombre'];
</pre>