views:

295

answers:

4

My goal is to store some html-formatted data in a variable, then echo it later.

For example:

<?php 
$foo = '<div id="x">';
echo $foo;
?>

The above doesn't work. Why?

Edit

Sorry for the bad question. I thought it didn't work because nothing is visible when viewed in a browser. Of course nothing is visible because there is only a div and no text. Doh! My "real life" version of the above script was broken due to an extra apostrophe.

+8  A: 

It probably works, but you're not seeing it because it's in the source code and not displayed visually on the web page.

Are you looking to actually display the source code in the web page? If so you will need to turn the < and > characters into &lt; and &gt; with htmlspecialchars.

meder
A: 

Works fine for me. The error must be somewhere else, check the error log?

Jeffrey Aylesworth
A: 
<?php 
$foo = '<div id="x">something</div>';
echo $foo;
?>

works for me. You did not close your div.

Nir Levy
+3  A: 

I don't see what wouldn't work in your example (unless stackoverflow mangled some of your characters). You're alternating the quotes. On the other hand, you didn't say what doesn't work. Is it a compile error or nothing is printed, or...?

does this work?

$foo = "<div id=\"x\">";

if there's a fair amount of html text, take a look at heredoc syntax.

$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;

or...

$mytext = <<<EOT
... a bunch of html text here ...
EOT;
wkw