开发者

How to write class/function that returns large amount of html

I'm used to using includes with large chunks of html outside of the php code, but I'm trying to move to classes or functions because they have increased flexibility and potential for design patterns etc.

I need a function right now that will return a large amount of html, mixed in with some php var开发者_如何学运维iables, but I'm looking for away to keep the code outside of the <?php declaration so that it will be formatted like proper html and have code hinting, rather than being a gigantic string.

If it's possible, how would I go about formatting/writing that?


I would do something like this...

function getPage() {
    ob_start();
    include("file_with_html.php");
    $content = ob_get_clean();
    return $content;
}

Of course, you can add other functionality as needed. But, the advantage here is that you're using output buffering. Without this, the data is sent to the user right away. But, using the ob_start() and ob_get_clean(), you can return it and work with it some more.


You can use include('somefile.html');.

include works with vanilla HTML too.

If you need to have it "mixed in with some php variables", just add those when you need them. Remember: PHP, by its very nature, is a templating language.

For example:

outerHTML.php:

<?php function generateCode($username) { ?>

    <h1>Welcome back, <?php echo $username; ?></h1>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>

<?php } ?>

main.php:

<?php

// some PHP code

include('outerHTML.php');

generateCode('John');

// some more PHP code

?>


Also, you can use output buffering within your classes. See comments at http://php.net/manual/en/function.ob-start.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜