1

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!

6 Answers 6

3

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;
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

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

Comments

0

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.

Comments

0

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

Comments

0

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;

Comments

0

Use heredoc syntax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.