Modify an Existing PHP Function to Return a String

You can make use of output bufferingDocs to get the output of that function:

ob_start();
get_header();
$html = ob_get_clean();

If you need that more than once, you can wrap it into a function of it’s own:

/**
 * call a function and return it's output as string.
 * 
 * @param callback $function
 * @param array $arguments (optional)
 * @param var $return (optional) the return value of the callback
 * @return string function output
 */
function ob_get_call($function, array $arguments = array(), &$return = NULL)
{
    ob_start();
    $return = call_user_func_array($function, $arguments);
    $buffer = ob_get_clean();
    return $buffer;
}

Usage:

$html = ob_get_call('get_header');

As the answer is that popular today, here is another function to get the output of an include:

/**
 * include a file and return it's output as string.
 * 
 * @param string $file
 * @param array $variables (optional) keys as variable names and values as variable values
 * @param var $includeReturn (optional) the return value of the include
 * @return string function output
 */
function ob_get_include($file, array $variables = array(), &$includeReturn = NULL)
{
    $includeFilename = $file;
    unset($file);
    extract($variables);
    unset($variables);
    ob_start();
    $includeReturn = include($includeFilename);
    return ob_get_clean();
}

Usage:

include.php:

<div class="greeting">
    Hello <em><?php echo htmlspecialchars($name); ?></em>!
</div>

Using:

$variables = array(
    'name' => 'Marianne',
);
$html = ob_get_include('include.php', $vars);

Related:

Leave a Comment