tags:

views:

84

answers:

6

I am generating a lot of HTML code via PHP, but I need to store it in a variable, not display it immediately. But I want to be able to break out of PHP so my code isnt a giant string.

for example (but actual code will be much larger):

<?php
$content = '<div>
    <span>text</span>
    <a href="#">link</a>
</div>';
?>

I want to do something like this:

<?php
$content = 
?>
<div>
    <span>text</span>
    <a href="#">link</a>
</div>
<?php
;
?>

But I know this will not return the html as a value it will just print it to the document.

But is there a way to do this tho?

Thanks!

+3  A: 

You can use output buffering:

<?php
ob_start();
?>
<div>
    <span>text</span>
    <a href="#">link</a>
</div>
<?php
$content = ob_get_clean();
?>

Or a slightly different method is HEREDOC syntax:

<?php
$content = <<<EOT
<div>
    <span>text</span>
    <a href="#">link</a>
</div>
EOT;
?>
Greg
A: 

Try this:

<?php
$var = <<<EOD
my long string
EOD;
echo $var; 
?>

(edit done, but one has edit faster than me :))

Aif
A: 

In my opinion, you should look into a template engine such as Smarty. It can help you take some of the ugliness out of hardcoding HTML into the PHP file, and can help make the code more manageable.

nasufara
A: 

You could store the html in an html file and read that file into a variable.

Daniel Bingham
A: 

While still technically a string, you might find the documentation on PHP's heredoc to be an entertaining read:

heredoc syntax

$content = <<<EOT

<div>
    <span>text</span>
    <a href="#">link</a>
</div>

EOT;
cballou
A: 

Use heredoc syntax.

mbeckish