将 html 括在 PHP 中的变量中

enclose html in variable in PHP

本文关键字:变量 PHP html 括在      更新时间:2023-09-26

所以,我在php中有几个html行:

function upload_image()
{
 ?>
  <div class="something">       
    <div class="soemthing le">
        <ul class="haha">           
            <div class="sdfd">
                <div class="sdde"></div>
            </div>  
        </ul>           
    </div>
 </div>
<?php
}

我正在尝试通过 ajax 将这些数据发送到 js。我不确定如何将所有内容都包含在一个变量中,然后我可以将其发送到 js。

有人可以告诉我如何将其包含在变量中吗?

谢谢

最简单(主观)的是 Heredoc 语法

$string=<<<HTML
<div class="something">       
    <div class="soemthing le">
        <ul class="haha">           
            <div class="sdfd">
                <div class="sdde"></div>
            </div>  
        </ul>           
    </div>
 </div>
HTML;

然后你可以回显你的字符串

echo $string;   // or return $string as need be

这样可以保持代码干净,也使您不必担心单引号双引号等。 使用引号,如果代码在相似的引号内,则始终必须对其进行转义。

HTML只是一个标记,它可以是任何东西,只是关闭占位符在其行上之前不应该有任何内容,甚至没有空格。

$a=<<<TESTING
Yeah that's nice. Heck with those double " or Single ' quotes :P
TESTING;

您可以在一个变量中设置此 html 数据,如下所示:

<?php
    $variable = "";
    $variable .=  '<div class="something">';
    $variable .=  '<div class="soemthing le">';
    $variable .=  '<ul class="haha">';
    $variable .=  '<div class="sdfd">';
    $variable .=  '<div class="sdde"></div>';
    $variable .=  '</div>';
    $variable .=  '</ul>';     
    $variable .=  '</div>';
    $variable .=  '</div>';
?>

像这样混合代码和模板(HTML)通常被认为是不好的形式。我建议

  • 使用模板库(如 Mustache)将代码和布局分开
  • 或者使用 MVC 框架(如 Laravel),它可以帮助您构建适当的应用程序结构,并使用开箱即用的模板和视图

或者,如果所有这些都太难了,至少从外部文件中读取 HTML,并将其放入变量中,如下所示

<?php 
    function upload_image() {
        $var = file_get_contents(TEMPLATE_DIR . "/upload_image.html");
    }
?>

在配置文件或其他东西的某个中心点,你做

<?php
    define('TEMPLATE_DIR', "[[path to template dir]]");
?>

像这样:

function upload_image()
{
  $var = "<div class='something'><div class='soemthing le'><ul class='haha'>           
            <div class='sdfd'><div class='sdde'></div></div></ul></div></div>";
}