views:

82

answers:

3

Hello there, I'm struggling trying to read a php file inside a php and do some manipulation..after that have the content as a string, but when I try to output that with echo or print all the php tags are literally included on the file.

so here is my code:

function compilePage($page,$path){
   $contents = array();
   $menu = getMenuFor($page);
   $file = file_get_contents($path);
   array_push($contents,$menu);
   array_push($contents,$file);
   return implode("\n",$contents);
}

and this will return a string like

<div id="content>
   <h2>Here is my title</h2>
   <p><? echo "my body text"; ?></p>
</div>

but this will print exactly the content above not compiling the php on it.

So, how can I render this "compilePage" making sure it returns a compiled php result and not just a plain text?

Thanks in advance

+1  A: 

You can use output buffering for this, and include the file normally:

function compilePage($page,$path){
   $contents = array();
   $menu = getMenuFor($page);
   ob_start();
   include $path;
   $file = ob_get_contents();
   ob_end_clean();
   array_push($contents,$menu);
   array_push($contents,$file);
   return implode("\n",$contents);
}

The include() call will include the PHP file normally, and <?php blocks will be parsed and executed. Any output will be captured by the buffer created with ob_start(), and you can get it later with the other ob_* functions.

zombat
+1 this is the best way.
Pekka
A: 

You need to use include() so it will execute. You can couple this with output buffering to get the return in a string.

function compilePage($page,$path){ $contents = array(); $menu = getMenuFor($page);

//output buffer
ob_start();
include($path);
$file = ob_get_contents();
ob_end_clean();   

array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);

}

Jage
+1  A: 
function compilePage($page, $path) {
    $contents = getMenuFor($page);
    ob_start();
    include $path;
    $contents .= "\n".ob_get_clean();
    return $contents;
}

To evaluate PHP code in a string you use the eval function, but this comes highly unadvised. If you have a file containing PHP code, you can evaluate it with include, include_once, require, or require_once depending on your need. To capture the output of an included file - or required, or whichever method - you need to enable output buffering.

erisco
thanks erisco, I'm not sure about the other solutions but this appeared to be the simplest one. :) cheers
ludicco