Search code examples
phpoutput-buffering

HTML into PHP Variable (HTML outside PHP code)


I am new to php and wondering if I can have something like this:

<?php
 ...
 magicFunctionStart();
?>

<html>
   <head>...</head>
   <body>...</body>
</html>

<?php
 $variable = magicFunctionEnd();
 ...
?>

What I have to use right now is

<?php
 ...
 $variable = "<html><head>...</head><body>...</body></html>"
?>

Which is annoying and not readable.


Solution

  • Have you tried "output buffering"?

    <?php
     ...
     ob_start();
    ?>
    
    <html>
       <head>...</head>
       <body>...<?php echo $another_variable ?></body>
    </html>
    
    <?php
     $variable = ob_get_clean();
     ...
    ?>