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?
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.
<?php
$my_var = <<<EOD
<div>SOME HTML</div>
EOD;
?>
It's called heredoc syntax.
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');
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.
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();
?>
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With