Question

I have an already built complex php application that doesn't work by the MVC design pattern and doesn't have a built-in templating system (twig etc).

What happens is that instead of getting a variable at the end that contains the template (html out put) -> it prints the html (include 'foo/somepagethatcontainshtmlandphp.php').

My problem? that page is requested from a remote server with ajax. I want to get that page encoded by JSON. and decode it on the remote server with json.parse.

My Question:

How can I encode an already printed out html output and render it to JSON. is it even possible?

Structure of my files: template/sometmp.php

<html>
  <head>
   <?php echo 'some shitty way to use html and php together'; ?>
  </head>
<body>
<?Php echo 'some lame php and html code written in the same place'; ?>
</body>
</html>

Index.php

Remote Server:

$.ajax (
      .....
      .....
      success: function(data) {
          console.log(JSON.parse(data));
      }
);

Thanks in advanced.

Was it helpful?

Solution

Use output buffering. E.g.:

ob_start();
include 'foo/somepagethatcontainshtmlandphp.php';
$html = ob_get_clean();

echo json_encode(array(
    'some_data' => ...,
    'html' => $html
));

Please, treat this code as a sketch, something you should start with. There are more things to consider, e.g. should I be using include or require or should I be using JSON or simply text response. The answers are up to you and depend on further logics of your application/website.

More info about output buffering in the documentation.

OTHER TIPS

If I understand your question right you can simple buffer the output of the include file give the buffer to json_encode and output this.

<?php
ob_start();
include 'foo/somepagethatcontainshtmlandphp.php'
$output = ob_get_clean()
echo json_encode($output);
?>

this could be parse by Javascript as json.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top