sea*_*boy 59 php string templating
我有一个PHP函数,我用它来输出标准的HTML块.它目前看起来像这样:
<?php function TestBlockHTML ($replStr) { ?>
<html>
<body><h1> <?php echo ($replStr) ?> </h1>
</html>
<?php } ?>
Run Code Online (Sandbox Code Playgroud)
我想在函数内部返回(而不是回显)HTML.有没有办法在不在字符串中构建HTML(上面)的情况下执行此操作?
Pau*_*xon 82
您可以使用支持变量插值的heredoc,使其看起来相当整洁:
function TestBlockHTML ($replStr) {
return <<<HTML
<html>
<body><h1>{$replStr}</h1>
</body>
</html>
HTML;
}
Run Code Online (Sandbox Code Playgroud)
但请密切注意手册中的警告 - 结束行不得包含任何空格,因此不能缩进.
Kon*_*lph 66
是的,有:你可以echo
使用ob_start
以下方法捕获ed文本:
<?php function TestBlockHTML ($replStr) { ob_start(); ?>
<html>
<body><h1> <?php echo ($replStr) ?> </h1>
</html>
<?php
return ob_get_clean();
} ?>
Run Code Online (Sandbox Code Playgroud)
Lor*_*une 16
这可能是一个粗略的解决方案,我很感激有人指出这是否是一个坏主意,因为它不是功能的标准用法.我已经成功地从PHP函数中获取HTML而没有将返回值构建为具有以下内容的字符串:
function noStrings() {
echo ''?>
<div>[Whatever HTML you want]</div>
<?php;
}
Run Code Online (Sandbox Code Playgroud)
刚刚'调用'函数:
noStrings();
Run Code Online (Sandbox Code Playgroud)
它将输出:
<div>[Whatever HTML you want]</div>
Run Code Online (Sandbox Code Playgroud)
使用此方法,您还可以在函数中定义PHP变量并在HTML中回显它们.
创建模板文件并使用模板引擎读取/更新文件.它将增加代码在未来的可维护性以及单独显示逻辑.
使用Smarty的一个例子:
模板文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>
Run Code Online (Sandbox Code Playgroud)
码
function TestBlockHTML(){
$smarty = new Smarty();
$smarty->assign('title', 'My Title');
$smarty->assign('string', $replStr);
return $smarty->render('template.tpl');
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用file_get_contents()并使用模板HTML页面
模板页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>
Run Code Online (Sandbox Code Playgroud)
PHP函数
function YOURFUNCTIONNAME($url){
$html_string = file_get_contents($url);
return $html_string;
}
Run Code Online (Sandbox Code Playgroud)