Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining html code inside PHP variables

I want to include html code inside php variables. I remember there was a way to define html code inside a php variable, something similar to this:

<?php $my_var = { ?>
<div>SOME HTML</div>
<?php } ?>

I found it on PHP.net but I can't find it now. There was something else instead of the "{" but I don't remember exactly. I am looking to directly write the html code like above, so NOT like this: $my_var = '<div>SOME HTML</div>'; Any ideas?

like image 542
adrianTNT Avatar asked Sep 05 '11 08:09

adrianTNT


6 Answers

Try this:

<?php ob_start(); ?>
<div>HTML goes here...</div>
<div>More HTML...</div>
<?php $my_var = ob_get_clean(); ?>

This way you will retain syntax highlighting for HTML.

like image 117
Irfanullah Jan Avatar answered Sep 27 '22 23:09

Irfanullah Jan


<?php
$my_var = <<<EOD
<div>SOME HTML</div>
EOD;
?>

It's called heredoc syntax.

like image 33
Emil Vikström Avatar answered Sep 27 '22 22:09

Emil Vikström


Save your HTML in a separate file: example.html. Then read in the contents of the file into a variable

$my_var = file_get_contents('example.html');
like image 43
bart Avatar answered Sep 27 '22 22:09

bart


If you don't care about HTML syntax highlighting you could just define a normal variable. You don't have to escape HTML either because PHP lets you use single quotes to define a variable, meaning you can use double quotes within your HTML code.

$html = '
 <p>
  <b><i>Some html within a php variable</i><b>
 </p>
 <img src="path/to/some/boat.png" alt="This is an image of a boat">
' ;

Works perfectly for me, but it's a matter of preference and implementation I guess.

like image 41
Mick Houtveen Avatar answered Sep 28 '22 00:09

Mick Houtveen


If you are going to be echoing the content then another way this can be done is by using functions,

this also has the added benefit of programs using syntax highlighting.

function htmlContent(){
?>
    <h1>Html Content</h1>
<?php
}


htmlContent();
?>
like image 43
RedSparr0w Avatar answered Sep 28 '22 00:09

RedSparr0w


To define HTML code inside a PHP variable:

1) Use a function (Ref: @RedSparr0w)

<?php
function htmlContent(){
?>

    <h1>Html Content</h1>

<?php
}
?>

2. Store inside a variable

$var = htmlContent();
like image 27
S R Panda Avatar answered Sep 27 '22 22:09

S R Panda