Search code examples
phpphp4

PHP: Breaking out of PHP for HTML but return as value instead of print on page?


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!


Solution

  • 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;
    ?>