在HTML中显示未解析的PHP

在HTML中显示未解析的PHP

问题描述:

I want to show unparsed PHP code in my HTML. For example, I want this to render in my HTML documents.

This is how you print text in PHP

<?php print "Hello!"; ?>

By printing the codes as a string with htmlspecialchars(), they will not be parsed by either your server or the browser.

echo htmlspecialchars('<?php print "Hello!"; ?>')

In HTML, use "&lt;" and "&gt;" for your '<' and '>' characters.

<p>This is how you print text in PHP</p>
&lt;?php print "Hello!"; ?&gt;

Have a look at the highlight_file function in PHP.

You pass in a file and it either prints out the source with syntax highlighting to screen or with an optional return parameter, you can echo it out where you want. Example: highlight_file($file) or echo highlight_file($file,true)

There are examples in the link to also get line numbers for the code.

Other methods require manually reading the file with other functions in PHP and/or require having the source code you want as strings in other files.

Using highlight_file is really good as you can have a working PHP file somewhere so a person can see what it does and very easily view the source with highlighting. This would be the best method for showing code as a tutorial or reference.

EDIT

You can also do highlighting of a value that is stored in a string with highlight_string