Elven6 Posted June 27, 2011 Share Posted June 27, 2011 Hello, I'm working on a php template system where I use file_get_contents() to fetch the template files. The template files are .php but mostly consist of html code with some php. Using file_get_contents() I'm able to get the files to load perfectly, the issue arises when there is php code in the template, specifically, code that requires a function referenced in a different file. The problem is the functions file (functions.php) is referenced in the main index.php file but for some reason, the template code doesn't seem to recognize that. If it helps, I use file_get_contents() like this, $templ = file_get_contents("".$url."/templates/index.php"); I noticed if I change the extension to something else (.html or even something fictional like .asd) the code runs just fine and the functions.php file is recognized by the php code. This is certainly an option but for convenience I'm hoping to keep the .php extensions. I tried using include(), require(), and even require_once() but the same issue arises concerning .php files. I haven't seen anything that says I can't use this method to load the files but it's possible I may have missed something. Is there an alternative method I can use if there's no solution here? Any help would be appreciated, Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/240484-file_get_contents-and-php-files/ Share on other sites More sharing options...
trq Posted June 27, 2011 Share Posted June 27, 2011 file_get_contents(0 doesn't make a request for the file via http, therefore the php is never parsed. A better options is to wrap the include construct. Something like.... function loadTemplate($template) { ob_start(); include $template; return ob_get_contents(); } This loads the template (parsing the php) into a buffer then returns the buffers contents. Quote Link to comment https://forums.phpfreaks.com/topic/240484-file_get_contents-and-php-files/#findComment-1235205 Share on other sites More sharing options...
Elven6 Posted June 27, 2011 Author Share Posted June 27, 2011 Thanks for your response, I noticed now that if I use ../ in place of the $url the file now seems to load properly with a .php extension. Would you recommend I use the code you posted or keep the file_get_contents() intact now that it works? I guess one of the benefits of using your code is it would be easier to change if I wanted to implement a new way of loading the templates versus the current method where I would need to make individual changes to each instance. Quote Link to comment https://forums.phpfreaks.com/topic/240484-file_get_contents-and-php-files/#findComment-1235212 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.