How can I echo HTML in PHP?

后端 未结 13 2448
耶瑟儿~
耶瑟儿~ 2020-11-22 06:40

I want to conditionally output HTML to generate a page, so what\'s the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework lik

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:09

    Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)

    $page = 'Hello, World!';
    $content = file_get_contents('html/welcome.html');
    $pagecontent = str_replace('[[content]]', $content, $page);
    echo($pagecontent);
    

    Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.

    It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)

    I.e.:

    
    

    My Template page says


    Template footer

提交回复
热议问题