0

I've got an ajax call returning some html. The html is created and returned in a function like so:

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

    return json_encode($returnObject);
}

What I'd like to do is write a .php file with all of my html and vars in it like this...

<form>
    <h1><?php echo $title ?></h1>
    <input type="text" name="title"/>
</form>

and then in my function import that file as a string with the vars set sorta like this:

function return_html(){
    $title = 'My Form';
    $returnObject = array();
    $returnObject['html'] = my_file_as_string_but_with_vars_replaced('formFile.php');   
    return json_encode($returnObject);
}

Thoughts?

2
  • Sounds you like you want to build a templating engine. Commented Nov 16, 2010 at 0:58
  • @hamish, something similar, although on a very small scale. Commented Nov 16, 2010 at 1:03

1 Answer 1

2

Perhaps

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

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

    return json_encode($returnObject);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm gonna ask before I try... will this replace my php vars with their values? I'm not 100% certain, but I imagine I'll get my php statements as a string... eg instead of replacing the 'echo $title' I'll actually see 'echo $title' in the output.
The variables will be replaced in the required file. In fact, all this is doing is evaluating the required file and capturing the output as a string. I've tested this on my personal web server, and it should work with php5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.