problem with < in a variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
casall
Forum Newbie
Posts: 2
Joined: Tue Dec 28, 2010 12:57 pm

problem with < in a variable

Post by casall »

Hi
I am having some problems with variables, hope that someone can help me out with this.

example code:
$a = "test";
$b = "<test>";
echo "$a"; -- prints: test
echo "$b"; -- prints: <nothing>

So as soon as I add "<" to the variable the variable is blank for some odd reason.

I have tried to escape it with \ but that doesn't make any difference, the $b will then only print \ and nothing else.

Running: PHP Version 5.2.6-2ubuntu4.6

Any suggestions?
casall
Forum Newbie
Posts: 2
Joined: Tue Dec 28, 2010 12:57 pm

Re: problem with < in a variable

Post by casall »

found a workaround...

$a = "< test>";

If there is a space between the < and the following text it will print...
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: problem with < in a variable

Post by McInfo »

View the HTML source in your browser.

The browser interprets a string like "<test>" as XML. Just like you don't see the PHP source code after running a PHP script, you don't see the markup language after it is rendered in your browser window.

The way to deal with that behavior is to encode certain characters so that, when the browser decodes them, they appear as they did before the encoding. If you encode the string "<test>" as "<test>", the browser will render it as "<test>". PHP has built-in functions for this purpose: htmlspecialchars(), htmlentities().

If you don't want to bother with encoding, change the Content-Type header to plain text (for good browsers that don't force download of text files).

Code: Select all

header('Content-Type: text/plain');
Post Reply