从函数返回html

时间:2012-08-07 00:37:17

标签: php html

因此,作为一个新手,这只是一个最佳实践问题,但最好从这样的函数返回html:

function returnHtml($userName)
{   
$htmlMsg = "
<html>
    <head>
        <title>Return the html</title>
    </head>
    <body>
        <p>You've received an email from: ".$userName.".</p>
    </body>
</html>
";

return $htmlMsg;
}

或者像这样:

function returnHtml($userName)
{
?>
<html>
    <head>
        <title>Return the html</title>
    </head>
    <body>
        <p>You've received an email from: <?php $userName ?>.</p>
    </body>
</html>
<?php
}

第二个比第一个容易得多,因为你不必将html变成一个字符串,但我想知道是否缺少return语句会导致任何不可预见的问题。谢谢你的任何建议!

2 个答案:

答案 0 :(得分:4)

您发布的两个功能做了不同的事情。第一个返回一个html字符串,第二个打印字符串。

基本上,这取决于你想用这个功能完成什么。如果你想打印一些HTML,第二个函数更好,如果你想在字符串中有一些HTML,第一个更好。

答案 1 :(得分:2)

如果您使用它来使用AJAX,GET或POST方法获取HTML代码,那么我将使用第一个,因为从php文件回显的任何内容都被放入您可以使用的变量中。

例如:

$.ajax({
    type: "POST",
    url: "document.php",
    data: {data: "some information to send"},
    success: function(echoed_data) {
        $('#element').html(echoed_data);
    }
});

document.php

function returnHtml($userName) {   
    $htmlMsg = "
        <html>
            <head>
                <title>Return the html</title>
            </head>
            <body>
                <p>You've received an email from: ".$userName.".</p>
            </body>
        </html>
    ";

    echo $htmlMsg;
}

这将使用AJAX从“document.php”发送和接收数据,然后输入从.php文件回显到某个元素的HTML代码。