PHP创建了一种更好的回显变量的方法
I am looking for a way to replace <?php echo $something; ?>
with another notation like {$something}
. But: No smarty or sth similar is used!
More detailed:
At the moment, I got a .php file (with some variables inside), which includes the file "template.php". In this template file, I don't want having to use the (not very user-friendly) php notation, but replace certain strings inside this file like mentioned above. Is there any way to do so? It would be probably the best, if you could replace strings like <title></title>
with <title><?php echo $title; ?></title>
.
Maybe (my thoughts) I should just write the whole code into a php variable, then do some preg_replace and echo it? Or is there a more beautiful solution?
Did a similar thing several years ago wherein I had to replace several variables in an email template. What I ended up implementing was doing a str_replace
on several tags. Like you, I don't want to have PHP notations or to escape characters in the template file as much as possible
Example:
template.php
<html>
<head>
<title>[EMAIL_TITLE]</title>
</head>
<body>
Hello [USER_NAME],
Login here [LOGIN_LINK].
</body>
</html>
processor.php
$body = file_get_contents( 'template.php' );
str_replace( '[EMAIL_TITLE]', $emailTitle, $body );
str_replace( '[USER_NAME]', $userName, $body );
str_replace( '[LOGIN_LINK]', $userName, $body );
I've sinced changed implementation though to make use of PHP short tags. Using the same previous example, you could try:
template.php
<html>
<head>
<title><?= $params['title']; ?></title>
</head>
<body>
Hello <?= $params['userName']; ?>!
</body>
</html>
processor.php
$params = array(
'title' => $siteTitle,
'userName' => $userName
);
ob_start();
require_once( 'template.php' );
$body = ob_end_clean();
There are a few notations you can try. One that I prefer for templates is simply:
<?php
echo <<<HTML
<html>
<head>
<title>$title</title>
</head>
<body>
$body
</body>
</html>
HTML;
?>
And then in your content file, you do something like:
<?php
$title = 'My Page!';
$body = '<p>My Content!</p>';
include './template.php';
?>
With this, you don't have to escape singe and double quotes, and it's easy to make changes later.
You can also read in the file to a string and use preg_replace like you said. The easiest way would be with an array to manually go through the file and pull out the place holders. But this is a slow solution if you have high traffic and a lot of variables.