Can php be modified to create a custom way to call a php function without opening and closing php tags? For example, given an example function like this that is incl
Most of the time a fancy template engine is entirely unnecessary. You can easily accomplish this by running a simple str_replace loop of your tokens and their values over the otherwise-ready HTML (that you've stored into a variable) before you echo it all out. Here's what I do:
$html = '<b>My-ready-HTML</b> with {{foo}} and {{bar}} thingys.';
// Or: $html = file_get_contents('my_template.html');
$footsy = 'whatever';
$barsie = 'some more';
$tags = [
'foo' => $footsy,
'bar' => $barsie
];
function do_tags($tags, $html) {
foreach ($tags as $key=>$val) {
$html = str_replace('{{'.$key.'}}', $val, $html);
}
return $html;
}
$output = do_tags($tags, $html);
echo $output;
A similar effect is achievable using short_tags. Instead of doing
<?php echo $blah ?>
do
<?= $blah ?>
or
<?= callFunction() ?>
If you have php version 5.4 or greater, these tags will be supported. Prior to that, short_tags are disabled by defaut. Even in 5.4+, they can be disabled by the server so use it wiseley.
Another way is to echo html in a string so you don't have to switch in and out of php. Just remember to keep it readable for yourself and others:
<?php
$text = "Hello, World!";
echo "<html>
<head>
</head>
<body>
<span>" . $text . "</span>
</body>
</html>";
You can also use heredocs:
$html = <<<HTML
<html>
<head>
</head>
<body>
<span>$text</span>
</body>
</html>
HTML;
echo $html;
Edit: I also wanted to point out ob_start and ob_get_clean. What this will do is "record" everything that should be printed out on the screen without printing it out. This allows you to complete all of the logic in your code before the contents are displayed on the screen. You still need to either open and close php tags or echo strings containing html.
<?php
ob_start();
$text = "Hello, World!";
?>
<html>
<head>
</head>
<body>
<span><?= $text ?></span>
</body>
</html>
<?php
$html = ob_get_clean();
echo $html; //All output stored between ob_start and ob_get_clean is then echoed onto the web page at this point.
This may not be helpful for small webpages that don't need to process a lot of information. But if you have a lot of information to be displayed. It's beneficial to send large chunks of data to HTML over sending lots of smaller bits and can increase performance.
Instead of:
<title><?php echo title(); ?></title>
Try using:
<title><?= title() ?></title>
Anything beyond that you may as well be using (and in a sense will be) a templating engine, because you'll have to parse the block of code and interpret the {{}} brackets.
You can store all html codes in PHP variable and print it out at the end, this method can avoid many open and closing PHP tag. Like this:
<?php
print "<html><head><title>".title()."</title></head><body></body></html>";
?>
instead of:
<html><head><title><?php echo title(); ?></title></head><body></body></html>