代码之家  ›  专栏  ›  技术社区  ›  Maksim Vi.

HTML到PHP变量(HTML在PHP代码之外)

  •  23
  • Maksim Vi.  · 技术社区  · 15 年前

    我刚接触过PHP,想知道我是否可以拥有这样的功能:

    <?php
     ...
     magicFunctionStart();
    ?>
    
    <html>
       <head>...</head>
       <body>...</body>
    </html>
    
    <?php
     $variable = magicFunctionEnd();
     ...
    ?>
    

    我现在要用的是

    <?php
     ...
     $variable = "<html><head>...</head><body>...</body></html>"
    ?>
    

    这很烦人,不可读。

    7 回复  |  直到 6 年前
        1
  •  66
  •   Wabbitseason    15 年前

    你试过“输出缓冲”吗?

    <?php
     ...
     ob_start();
    ?>
    
    <html>
       <head>...</head>
       <body>...<?php echo $another_variable ?></body>
    </html>
    
    <?php
     $variable = ob_get_clean();
     ...
    ?>
    
        2
  •  15
  •   eplawless    15 年前

    我想你想要 heredoc 语法。

    例如:

    $var = <<<HTML
    <html>
       <head>
    random crap here
    </html>
    HTML;
    
        3
  •  4
  •   Christian C. Salvadó    15 年前

    我不太确定你想完成什么,但我认为 heredoc syntax 可能对你有用:

    <?
    $variable = <<< MYSTRING
    
    <html>
       <head>...</head>
       <body>...</body>
    </html>
    
    MYSTRING;
    

    但是,如果您试图创建HTML模板,我强烈建议您使用真正的模板引擎,例如 Smarty ,请 Dwoo Savant .

        4
  •  1
  •   Toby Allen mercator    11 年前

    好吧,你想做的事情在某种程度上是可能的。

    不能简单地将HTML块分配给PHP变量,也不能使用函数来分配。然而,有很多方法可以得到你想要的结果。

    1. 调查模板引擎的使用情况(我建议您这样做,因为无论如何它是值得的)。我用 smarty 但是还有很多其他的
    2. 第二种方法是使用输出缓冲区。

    其中一个问题是,页面中的任何HTML都会立即发送到客户机,这意味着它不能在PHP中用作变量。但是,如果使用函数 开始和结束你可以实现你想要的。

    <?php 
      somesetupcode();
      ob_start();  ?>
    <html>
    <body>
    html text
    </body>
    </html>
    <?php
      //This will assign everything that has been output since call to ob_start to your    variable.
      $myHTML = ob_get_contents() ;
      ob_end_flush();
    
    ?>
    

    希望这能帮助你了解 output buffers 在PHP文档中。

        5
  •  0
  •   T.Todua Laurent W.    6 年前

    我总是建议 避免 缓冲功能(如 ob_start 或等)每当您有其他选择时(因为有时它们可能与同一系统中的部件冲突)。

    我使用:

    function Show_My_Html(){ ?> 
        <html>
          <head></head>
          <body>
             ...
          </body>
        </html>
        <?php 
    }
    
    //output anywhere
    Show_My_Html();
    
        6
  •  0
  •   trainmania100    6 年前
    $html_content = '
        <p class="yourcssclass">Your HTML Code inside apostraphes</p>
    ';
    echo $html_content;
    
        7
  •  -8
  •   gfsd4gs56g14sd56    11 年前

    这真的很疯狂,但要知道,如果你这样做:

    <?php echo ""; ?>  
    

    你会得到它:

    <html><head></head><body></body></html>  
    

    保持冷静,这是唯一让你发疯的PHP。