Search code examples
phpfunctionoutputeval

Function to execute a string as PHP code and return the printed text from code


I am trying to create a function that would parse php code and return the result in pure text, as if it was being read in a browser. Like this one:

public function PHPToText($data, $php_text) {
    //TODO code
    return $text; 
}

I would call the function like this, with the params that you see below:

$data = array('email' => 'test@so.com');
$string = "<?= " . '$data' . "['email']" . "?>";

$text = $this->PHPToText($data, $string);

Now echo $text should give: test@so.com

Any ideas or a function that can achieve this nicely?


Solution

  • It's a bad bad bad bad bad idea, but basically:

    function PHPToText($data, $string) {
        ob_start();
        eval($string);
        return ob_get_clean();
    }
    

    You really should reconsider this sort of design. Executing dynamically generated code is essentially NEVER a good idea.