note 61323 deleted from function.eval by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 19:58:00 +0000 |
| Subject: | note 61323 deleted from function.eval by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155302@lists.php.net to get a copy of this message | ||
Note Submitter: karig at karig dot net
----
OK, here's what I've found to work for me:
Let's say I have a string like this, pulled from a much larger file:
$text = "<p>The following is generated by PHP:</p>\n"
. '<?php $a = 6; $b = 4; $c = $a + $b; '
. 'echo "<p>Variable c = $c</p>\n"; ?>'
. "<p>This is just more text.</p>\n";
Doing this just echoes the PHP code (so a visitor can actually read it by viewing the web
page's source) instead of executing it:
echo $text;
I wanted to have the PHP code in the text executed, so that the /result/ is echoed, and the code
itself is not. Happily, all I needed to do to get this to work for me was this:
ob_start();
eval ('?>' . $text);
$text = ob_get_clean();
// Do whatever else you want with $text before outputting it
echo $text;
That little '?>' prepended to $text (suggested by a previous note here) seems to be the
key. Note that I DON'T append a corresponding '<?php' to $text, as a previous note
suggested; I tried that, and I got an error. But I've found that "eval ('?>'
. $text);" works:
---- OUTPUT ----
The following is generated by PHP:
Variable c = 10
This is just more text.
---- HTML REVEALED IN WEB-PAGE SOURCE ----
<p>The following is generated by PHP:</p>
<p>Variable c = 10</p>
<p>This is just more text.</p>