在 PHP 变量中定义 html 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7305869/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:26:36  来源:igfitidea点击:

Defining html code inside PHP variables

phphtmlvariables

提问by adrianTNT

I want to include html code inside php variables. I remember there was a way to define html code inside a php variable, something similar to this:

我想在 php 变量中包含 html 代码。我记得有一种方法可以在 php 变量中定义 html 代码,类似于:

<?php $my_var = { ?>
<div>SOME HTML</div>
<?php } ?>

I found it on PHP.netbut I can't find it now. There was something else instead of the "{"but I don't remember exactly. I am looking to directly write the html code like above, so NOT like this: $my_var = '<div>SOME HTML</div>';Any ideas?

我在网上找到了,PHP.net但现在找不到了。还有其他东西而不是,"{"但我不记得了。我想直接编写上面的 html 代码,所以不是这样:有$my_var = '<div>SOME HTML</div>';什么想法吗?

回答by erfan

Try this:

尝试这个:

<?php ob_start(); ?>
<div>HTML goes here...</div>
<div>More HTML...</div>
<?php $my_var = ob_get_clean(); ?>

This way you will retain syntax highlighting for HTML.

这样,您将保留 HTML 的语法突出显示。

回答by Emil Vikstr?m

<?php
$my_var = <<<EOD
<div>SOME HTML</div>
EOD;
?>

It's called heredocsyntax.

它被称为heredoc语法。

回答by bart

Save your HTML in a separate file: example.html.Then read in the contents of the file into a variable

将您的 HTML 保存在一个单独的文件中:example.html.然后将文件的内容读入一个变量

$my_var = file_get_contents('example.html');

回答by RedSparr0w

If you are going to be echoing the content then another way this can be done is by using functions,

如果您要回显内容,那么另一种方法是使用函数,

this also has the added benefit of programs using syntax highlighting.

这还具有使用语法突出显示的程序的额外好处。

function htmlContent(){
?>
    <h1>Html Content</h1>
<?php
}


htmlContent();
?>

回答by Mick Houtveen

If you don't care about HTML syntax highlighting you could just define a normal variable. You don't have to escape HTML either because PHP lets you use single quotes to define a variable, meaning you can use double quotes within your HTML code.

如果您不关心 HTML 语法突出显示,您可以只定义一个普通变量。您也不必转义 HTML,因为 PHP 允许您使用单引号来定义变量,这意味着您可以在 HTML 代码中使用双引号。

$html = '
 <p>
  <b><i>Some html within a php variable</i><b>
 </p>
 <img src="path/to/some/boat.png" alt="This is an image of a boat">
' ;

Works perfectly for me, but it's a matter of preference and implementation I guess.

非常适合我,但我猜这是一个偏好和实施问题。

回答by S R Panda

To define HTML code inside a PHP variable:

要在 PHP 变量中定义 HTML 代码:

1) Use a function (Ref: @RedSparr0w)

1) 使用函数 (Ref: @RedSparr0w)

<?php
function htmlContent(){
?>

    <h1>Html Content</h1>

<?php
}
?>

2. Store inside a variable

2. 存储在一个变量中

$var = htmlContent();