I just started learning php, And I'm stuck on how to write php code snippet inside html.
When I try <pre>
, and <code>
the php code starts running itself. I have named the file as run.php and I want to show this code as a snippet like the below one
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
And I want to show as it is, I don't want run the code. Please help me with this and thanks in advance.
CodePudding user response:
This has been closed as a duplicate of display-html-in-html and while, in principle the same applies here, there are some notable caveats.
The PHP interpreter is looking for the magic string "<?php" - that's what you need to encode in the source file to prevent PHP execution. And also any occurrence of "?>" within your snippets. You can apply the substitutions documented, or simply break the string:
print "<?" . "php";
However you still need to encode other stuff to prevent it being interpreted as a directive to the browser.
PHP provides a function for doing this: htmlentities()
This will automatically replace any of the control structures used in HTML.
But PHP goes further - specifically for rendering PHP source code, you can use the highlight_file() and highlight_string() functions. These will do the character replacements but also apply colours to the output to make it easier to visualize.
(there's also third party libraries, e.g. GeSHi, which can do this for PHP and other programming languages).
I would recommend you consider using highlight_file() to keep the PHP content you want to show separate from the code you want to execute - it can get quite confusing when you are only embedding PHP in HTML or vice-versa - as you add layers ots going to get confusing as to what is code and what is content.
CodePudding user response:
I would personally use highlight_string()
:
<?php
$mycode = <<<CODE
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
CODE;
highlight_string($mycode);
?>
Live example: http://135.125.201.97/so0001.php (exactly the code above)
It's a nice function, as it colorizes the PHP syntax. Please note that highlight_string()
echoes the code by default. If you want to use echo
you need to set the second parameter to true:
echo highlight_string($mycode,true);
Read more here.
Also check this answer (about how to use <<<
and what does it do).