Suppose we have something like this:
<?php
while(some statement here)
{
echo "some HTML here";
//..................
}
?>
As you know we can do it like this :
<?php
while(some statement here)
{?>
some HTML here
..............
<?php
} ?>
Now,What if I have something like this?
<?php
function example(){
$out="";
while(some statement here)
{
$out.="some HTML here";
$out.="some other HTML here";
//.......................
}
return $out;
}
?>
How can I get the HTML code out of <?php ?>
so it'll be more readable and can be edited easily using an editor like NotePad++ ? Thanks in advance
So if you want better syntax highlighting you need to close the php tags. Output buffering is a clean way to do this and it lets you maintain syntax highlighting in notepad ++. http://php.net/manual/en/book.outcontrol.php
<?php
function example(){
$foo = "Hello Again";
ob_start();
while(some statement here)
{
?>
<div id="somediv">Hello!</div>
<div id="somephpvar"><?php echo $foo;?></div>
<?php
}
return ob_get_clean();
}
?>
Short answer: Use output buffer control ( http://php.net/manual/en/book.outcontrol.php )
Example
<?php
function example(){
ob_start();
$i = 0;
while($i < 10)
{
?>
Hello<br/>
<?php
$i++;
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
echo example();
Long answer: You'd want to use a template engine like Twig ( https://twig.sensiolabs.org/ ) to have HTML outside of PHP code completely (of course with a lot more of benefit)
If you want to write the function yourself, the best way is using output buffering control , eg:
<?php
function() {
ob_start();
?>
<h1>Hello world</h1>
<?php
return ob_get_clean();
}
However, it is higly recommended that you use a template library, such as mustache . Most PHP frameworks include their own template mechanism; have a look at laravel , and cakePHP
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.