Reputation: 368
How do I print php code in a print / echo ?
What I mean is this:
<?php echo "<?php ?>"; ?>
Should output: <?php ?>
on my screen, but I receive a blank page. Any special escaping that I have to use ?
Upvotes: 4
Views: 1278
Reputation: 13552
There is another solution built on str_replace which accepts arrays for its parameters search and replace.
<?php
echo str_replace(array('<','>'),array('<','>'),'<?php ?>');
?>
Check out the following demo: http://phpfiddle.org/main/code/3hp-itx
Upvotes: 0
Reputation: 1303
If you print and you pretend to see it as HTML, the browser will interprete the tag and show nothing, but you will still be able to see it if you look at the source code. To show the < and > tags properly you should use < and > or use the htmlentities() or htmlspecialchars() functions:
<?php
echo htmlentities( '<?php ?>' );
?>
Upvotes: 1
Reputation: 10351
Akam's solution sorts out the PHP, if the Content-Type of the returned file is HTML.
Alternately, you could change the Content-Type to Text, thereby bypassing the HTML rendering.
<?php
header( 'Content-type: text/plain' );
echo '<?php ?>';
?>
Of course, this would affect the whole page, and not just a segment of it. As such, it would be useful it you were displaying the contents of a PHP script file as a standalone page, but if you were wanting to show snippets of PHP code within an HTML page, then Akam's solution would be better suited for that.
Upvotes: 2