Reputation: 611
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).
$response=array(
'result' => 1,
'error' => 0,
'someVar' => 'abc',
'outputHTML' => '<table>....</table>',
);
echo @json_encode($response);
die();
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()
{
$response=array();
//of course below code doesn't work
$response['outputHTML']=include('table-html.php');
echo @json_encode($response);
die();
}
where table-html.php file includes:
<table>
...
</table>
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.
UPDATE
In fact this code will work:
$response['outputHTML']=include('table-html.php');
if the table-html.php has the following content:
<?php
$output = '<table>'.$some_var.'</table>';
return $output;
Upvotes: 2
Views: 2964
Reputation: 1558
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');
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.
Example
<?php
return <<<EOT
<table>
<tr><td>$firstname</td><td>$lastname</td></tr>
</table>
EOT;
Upvotes: 7