faqts : Computers : Programming : Languages : PHP : Common Problems : Variables

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 21 people (86%) answered Yes
Recently 6 of 7 people (86%) answered Yes

Entry

How could I echo a variable which include "<? XXX ?>"

Feb 2nd, 2002 12:08
Philip Olson, Matt Gregory, Matthew Ma, Nathan Wallace,


I can see where this one would cause you trouble.  You want the browser
to output PHP code in HTML and not have it parsed.
You have to avoid two parsing conflicts when you echo this return 
variable.  First, PHP sees <? as the beginning of a script, and it 
sees ?> as the end of a script.  To avoid this problem make sure that 
the return variable is inside of single quotes like a string '<?'.  That
way it will not be parsed.
The second problem is the browser itself, which sees < as the 
beginning of an HTML tag.  You need to change < and > to entity form, 
htmlentities() can do this.
Try this example and be sure to view your HTML source :
  <?php
    $foo = 'hi';
    $a = '<? echo $foo; ?>';  // $foo remains as $foo
    $b = "<? echo $foo; ?>";  // $foo becomes 'hi'
    $c = htmlentities($a);    // < and > are converted
    print "$a <br>\n $b <br>\n $c";
  ?>
All strings are printed, but only $c shows in the browser.  It ($c) 
actually ends up looking like this :
  <? echo $foo; ?>
For related information, see:
  http://www.php.net/htmlentities  (or htmlspecialchars)
  http://www.php.net/manual/en/language.types.string.php
  http://www.zend.com/zend/tut/using-strings.php