Tuesday, February 28, 2012

Get the dynamically rendered file contents

/**
 * Get the dynamic rendered contents of given file
 * without exposing a bit of char.
 *
 * @author Junaid Atari <mj.atari@gmail.com>
 * @version 1.0
 * @param string $filename Absolute path of the file.
 * @param array $vars List of variables pass to file.
 * @return mixed Rendered output of file.
 */
function getIncludedFileContents $filename, array $vars = array () )
{
    
//** make sure that given path is the real file.
    
if ( is_file ( (string) $filename ) )
    {
        
//** Start Output Buffer
        
ob_start ();
        
ob_implicit_flush false );
     
        
//** Extract named variables and assign thier values.
        
extract $varsEXTR_PREFIX_SAME'vars' );
     
        
//** Include the file and execute the code.
        
require_once ( $filename );
     
        
//** Return the rendered output.
        
return ob_get_clean ();
    }

    
//** If nothing, return.
    
return NULL;
}
/*
 +-----------+
 |  Example  |
 +-----------+
*/
/*

welcome.php
-------------------
Salam <strong><?php echo $fullname; ?></strong>!

*/

/*
# The file contain variable $fullname
# and will replaced with the value.
echo getIncludedFileContents (
    "welcome.php",
    array ( "fullname"=>'Junaid Atari' )
);
*/

/*
 +-----------+
 |  Output   |
 +-----------+
*/
/*
Salam <strong>Junaid Atari</strong>!
*/