-1

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?

3
  • 1
    i am having trouble understanding what the function should do.. Commented Oct 5, 2011 at 15:57
  • I've voted up all answers for remembering the bads of eval(), though don't be afraid to use it. Just take care what you are evaling. Of course dont eval directly user input, but use it nevertheless. All php functions have a reason to be there. Commented Oct 5, 2011 at 16:02
  • php code is never read by the browser, the server does everything. Commented Oct 5, 2011 at 16:07

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

in this case it should be done with eval()

But always remember: eval is evil!

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.