使用PHP变量将HTML作为字符串导入

使用PHP变量将HTML作为字符串导入,php,Php,我接到一个ajax调用,返回一些html。html是在如下函数中创建和返回的: function return_html(){ $title = 'My Form'; $returnObject = array(); $returnObject['html'] = ' <form> <h1>' . $title . '</h1>

我接到一个ajax调用,返回一些html。html是在如下函数中创建和返回的:

function return_html(){
    $title = 'My Form';
    $returnObject = array();
    $returnObject['html'] = '
                <form>
                    <h1>' . $title . '</h1>
                    <input type="text" name="title"/>
                </form>
    ';

    return json_encode($returnObject);
}
想法?

也许吧

function return_html() {
    $title = 'My Form';

    ob_start();
    require 'formFile.php';
    $returnObject = array('html' => ob_get_clean());

    return json_encode($returnObject);
}

听起来你想建立一个模板引擎。@hamish,类似的东西,虽然规模很小。在我尝试之前我会先问一下。。。这会用它们的值替换我的php变量吗?我不是100%确定,但我想我会把我的php语句作为字符串。。。例如,我将在输出中实际看到“echo$title”,而不是替换“echo$title”。变量将在所需文件中替换。事实上,所有这些都是评估所需的文件并将输出捕获为字符串。我已经在我的个人web服务器上测试过了,它应该可以与php5一起使用。
function return_html(){
    $title = 'My Form';
    $returnObject = array();
    $returnObject['html'] = my_file_as_string_but_with_vars_replaced('formFile.php');   
    return json_encode($returnObject);
}
function return_html() {
    $title = 'My Form';

    ob_start();
    require 'formFile.php';
    $returnObject = array('html' => ob_get_clean());

    return json_encode($returnObject);
}