4

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 ?

1

4 Answers 4

12
<?php echo htmlspecialchars('<?php ?>'); ?>
Sign up to request clarification or add additional context in comments.

1 Comment

if you see the page, the <?php ?> was there, but the browser not render it as visual element because its for scripts, that's why you should out put it as entities.
2

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.

Comments

1

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 &lt; and &gt; or use the htmlentities() or htmlspecialchars() functions:

<?php
  echo htmlentities( '<?php ?>' );
?>

Comments

0

There is another solution built on str_replace which accepts arrays for its parameters search and replace.

<?php
 echo str_replace(array('<','>'),array('&lt;','&gt;'),'<?php ?>');
?>

Check out the following demo: http://phpfiddle.org/main/code/3hp-itx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.