将 HTML 内容分配给 PHP 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5563001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning HTML contents to PHP variables
提问by Shahid Karimi
Hard to explain, how to assign HTML contents to PHP variables. The HTML contents are not within the PHP script.as
很难解释,如何将 HTML 内容分配给 PHP 变量。HTML 内容不在 PHP script.as 中
<?php $a_div = ?><div>Contents goes <b>here</b></div>
回答by Robik
Try with ob_get_contents: ob_get_contents()
or ob_get_clean()
尝试使用 ob_get_contents:ob_get_contents()
或ob_get_clean()
<?php ob_start(); ?>
<div>Contents goes <b>here</b></div>
<?php $contents = ob_get_contents(); ?>
回答by Your Common Sense
If its raw HTML, with no PHP in it, stored in separate file it would be just
如果它的原始 HTML 中没有 PHP,存储在单独的文件中,它将只是
$a_div = file_get_contents('email.html');
If it's PHP file with HTML mixed with PHP then include it using output buffering like in Robik's answer.
如果它是带有 HTML 与 PHP 混合的 PHP 文件,则使用输出缓冲包含它,如 Robik 的答案。
ob_start();
include 'mail.template.php';
$a_div = ob_get_contents();
But if it's relatively small, I'd use HEREDOC
但如果它相对较小,我会使用 HEREDOC
$a_div = <<<HERE
<div>Contents goes <b>here</b></div>
HERE;
回答by HBublitz
If needed (normally I'm using html templates, replacing placeholders by php) ... there are two ways:
如果需要(通常我使用 html 模板,用 php 替换占位符)......有两种方法:
$testVar = <<<EndOfHtml
<div style="border: 48px solid red">test</div>
EndOfHtml;
print $testVar
the easier way, not too elegant - wrap html code in single quotes. so you don't have to escape any double quote:
更简单的方法,不太优雅 - 用单引号包裹 html 代码。所以你不必逃避任何双引号:
$test_var = '<div style="border: 48px solid red">test</div>'
helpful? :-)
有帮助吗?:-)
回答by cyan_jeff
Are you looking for token-terminated Block-Strings? http://www.phpf1.com/tutorial/php-heredoc-syntax.html
您在寻找以令牌结尾的 Block-Strings 吗? http://www.phpf1.com/tutorial/php-heredoc-syntax.html
Best I can do. Unfortunately your question is a little vague.
尽我所能。不幸的是,你的问题有点含糊。
回答by Nick Kuznia
It's a bit late, and it's not exactly what was asked, but if you're looking to render the page out of order (such as with templating), one could also wrap that section with a function and call it to render it in the desired location.
有点晚了,这不是所要求的,但是如果您希望按顺序呈现页面(例如使用模板),还可以使用函数包装该部分并调用它以将其呈现在理想位置。
<?php function RenderFooter() { ?>
<footer>some footer</footer>
<?php } ?>
<h1>Some header</h1>
<main>Some content</main>
<?= RenderFooter(); ?>
回答by Headshota
you can use DOMDocumentTo parse html file and get contents you need.
您可以使用DOMDocument来解析 html 文件并获取您需要的内容。