tags:

views:

148

answers:

7

It might be a bit unusual, but I need to echo <?php. However, I think that PHP treats it as an actual <?php and starts executing code instead of treating it as a string. How can I escape <?php and ?> so they can be treated as strings? There was nothing in the manual about this.

Thanks, I know this is a bit unusual.

A: 

If they are echoed in a string they will not be executed.

Cfreak
Nor will they be displayed on-screen (certainly not on my machine Ubuntu9.10, Apache2.2.12, php5.2) using `echo "<code><?php echo \"\$this_var\"; ?></code>";`
David Thomas
@ricebowl That seems to be my issue, I am not seeing anything at all
Cyclone
Nah. The code should be either executed, or visible in the source code. Are you sure it's neither?
Pekka
The problem with this is that the browser assumes that the stuff between the opening and the closing bracket (is that the correct word) is just another tag. But it doesn't know it, so it is simply not displayed. That's why you have to use the HTML entities < and > as mentioned about five times above.
Franz
Right but the OP asked how to get it to not execute which is a non-question, since it doesn't. Kudos to those who figured out what the OP meant rather than what he asked :)
Cfreak
+2  A: 

just use htmlentities function

Nazariy
How to do this?
Cyclone
`echo htmlentities("<?php")`
Ben James
+2  A: 

You can use the &lt; and &gt; html entities (to replace '<' and '>'). These are only handled in the browser, so PHP would not attempt to run that code.

Lior Cohen
Will this work if I wanted to write to a file?
Cyclone
Need more information. I don't see why not tho.
Lior Cohen
I am attempting to dynamically generate a php file, and it needs to be able to write it. When I tried it, it didn't work at all...
Cyclone
It wound up writing the actual '<' and '>' instead of the tags themselves.
Cyclone
Fixed it, thanks for the help!!!
Cyclone
+1  A: 

In HTML,

&lt;?php

Or in PHP:

echo htmlentities('<?php');
philfreo
+2  A: 

<?php echo "<?php echo \"hello\" ?>" ?>

prints out <?php echo "hello" ?>

Check out PHP's sourcecode of functions on how they print out data.

http://in2.php.net/source.php?url=/manual/en/function.htmlentities.php

Sairam Kunala
+1  A: 

If this is your code:

<?php
  echo '<?php';
?>

And you run that as a web page, you will see nothing. But not because PHP is not echoing your string <?php, but because the browser sees < and thinks that's the start of a tag, and tags are not displayed. It's obviously an error, but that's what the browser is doing.

To get around this, escape the < part, use htmlentities():

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

Which when it gets echoed, will result in HTML source of:

&lt;php

Which when displayed in the browser shows:

<?php

artlung
A: 
echo '<?php ?>'; // prints <?php ?>
echo "<?php ?>"; // prints <?php ?>

No, you do not have to do anything special.

Sidnicious