Is there any way to return HTML in a PHP function? (without building the return value as a string)

后端 未结 8 1721
误落风尘
误落风尘 2020-12-12 11:55

I have a PHP function that I\'m using to output a standard block of HTML. It currently looks like this:


          


        
相关标签:
8条回答
  • 2020-12-12 12:06

    You can use a heredoc, which supports variable interpolation, making it look fairly neat:

    function TestBlockHTML ($replStr) {
    return <<<HTML
        <html>
        <body><h1>{$replStr}</h1>
        </body>
        </html>
    HTML;
    }
    

    Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.

    0 讨论(0)
  • 2020-12-12 12:15

    Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.

    An example using Smarty:

    Template File

    <!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>
    

    Code

    function TestBlockHTML(){
      $smarty = new Smarty();
      $smarty->assign('title', 'My Title');
      $smarty->assign('string', $replStr);
      return $smarty->render('template.tpl');
    }
    
    0 讨论(0)
  • 2020-12-12 12:15

    Template File

    <h1>{title}</h1>
    <div>{username}</div>
    

    PHP

    if (($text = file_get_contents("file.html")) === false) {
        $text = "";
    }
    
    $text = str_replace("{title}", "Title Here", $text);
    $text = str_replace("{username}", "Username Here", $text);
    

    then you can echo $text as string

    0 讨论(0)
  • 2020-12-12 12:17

    Another way to do is is to use file_get_contents() and have a template HTML page

    TEMPLATE PAGE

    <!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>
    

    PHP Function

    function YOURFUNCTIONNAME($url){
    
    $html_string = file_get_contents($url);
    return $html_string;
    
    }
    
    0 讨论(0)
  • 2020-12-12 12:23

    Or you can just use this:

    <?
    function TestHtml() { 
    # PUT HERE YOU PHP CODE
    ?>
    <!-- HTML HERE -->
    
    <? } ?>
    

    to get content from this function , use this :

    <?= file_get_contents(TestHtml()); ?>
    

    That's it :)

    0 讨论(0)
  • 2020-12-12 12:24

    If you don't want to have to rely on a third party tool you can use this technique:

    function TestBlockHTML($replStr){
      $template = 
       '<html>
         <body>
           <h1>$str</h1>
         </body>
       </html>';
     return strtr($template, array( '$str' => $replStr));
    }
    
    0 讨论(0)
提交回复
热议问题