luqita
luqita

Reputation: 4077

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' => '[email protected]');
$string = "<?= " . '$data' . "['email']" . "?>";

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

Now echo $text should give: [email protected]

Any ideas or a function that can achieve this nicely?

Upvotes: -1

Views: 613

Answers (3)

Marc B
Marc B

Reputation: 360732

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.

Upvotes: 4

Ben Swinburne
Ben Swinburne

Reputation: 26477

You will need to use the eval() function http://www.php.net/eval in order to parse the tags inside your variable $string

Upvotes: 2

Stephan
Stephan

Reputation: 357

in this case it should be done with eval()

But always remember: eval is evil!

Upvotes: 4

Related Questions