Skip to content

Instantly share code, notes, and snippets.

@stnc
Last active August 19, 2023 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stnc/cc23d946f5e847dc60bf117b2680612a to your computer and use it in GitHub Desktop.
Save stnc/cc23d946f5e847dc60bf117b2680612a to your computer and use it in GitHub Desktop.
PHP capture print/require output in variable
<?php
function renderHtml($name) {
$path = $name;
if (file_exists($path) == false) {
throw new Exception('View not found in '. $path);
return false;
}
ob_start();
require($path);
$output = ob_get_clean();
return $output;
}
file_put_contents("template.html", renderHtml("body.php"));
echo renderHtml("body.php");
<?php
$content = '<div id="top"></div>';
$content.= renderHtml('title.php');
print($content);
<?php
$content = '<h1>Page heading</h1>';
print($content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment