ArturoO ArturoO - 1 year ago 52
PHP Question

Include file content in the variable

In my applications I often use AJAX calls to get certain variables along with html code, sampe JSON:

'result': '1',
'error': '0',
'someVar': 'abc',
'outputHTML': '<table>....</table>',

to create such JSON I have to assign each value in the associative array and encode it (server side: PHP code).

'result' => 1,
'error' => 0,
'someVar' => 'abc',
'outputHTML' => '<table>....</table>',
echo @json_encode($response);

I have my HTML code directly inside my classes, but I would like to move it into a separate template file to reduce class size and separate class code from html code. The problem is that I'm unable to get template code into a variable, sample:

function ajax_response()
//of course below code doesn't work
echo @json_encode($response);

where table-html.php file includes:


One solution to the problem is to use output buffering to catch the content of table-html.php file and insert it into the variable. The downside is that the output buffering isn't always enabled on servers, so on some hostings such code wouldn't work correctly.
Do you have any suggestions on alternative solutions to the problem ?

Note: Template files use PHP code to generate dynamically the HTML code, so the included PHP file must be parsed.


In fact this code will work:


if the table-html.php has the following content:

$output = '<table>'.$some_var.'</table>';
return $output;

Answer Source

include and require are used to load PHP code into your application.

To get the content of a file and store it in a variable use file_get_contents instead.
Do note that given path to the file is relative to the entry script. This might give unexpected results when your script is included from somewhere else. To counter this, use the __DIR__ magic constant.

Final code would look like:

$response['outputHTML'] = file_get_contents(__DIR__ . '/table-html.php');

If you want to parse PHP however

First of all, you might want to look at a templating engine like Twig, and save yourself some trouble.

If you want to do it yourself, the only thing you need to change in your code is to return a variable at the end of table-html.php. I'd suggest using Heredoc to create readable and easy templating.


    return <<<EOT