Putting PHP code in a string

Putting PHP code in a string

How do I put PHP Code into a string?
$phpCode = '';

For some reason, when I do this and echo out the code, I don't get the opening PHP tag, 

Solutions/Answers:

Answer 1:

Use htmlspecialchars():

$phpCode = '<? if($condtion){ ?>';
echo htmlspecialchars($phpCode);

Answer 2:

You need to echo htmlspecialchars($phpCode);

Answer 3:

try these $str= htmlentities('<?php //***code***// ?>');

Answer 4:

You can also use HTML entities.

When you replace just the opening square bracket in PHP, the rest will be considered a string when parsed with echo:

<?php
    //&lt; is the HTML entity for '<' (without quotes).
    $str = '&lt;?php yourstring ?>';
    echo $str;
?>

Source HTML Entities

Answer 5:

You can output PHP code as text in following way

$phpCode = '<? if($condtion){ ?>';
echo "<pre>";
echo htmlspecialchars($phpCode);
echo "</pre>";

Answer 6:

There's already a few answers to this, but just to add my $0.02...

This code:

<?php
    $test = '<?php echo "hello world!"; ?>';
    echo $test;
?>

Produces a blank white screen in the browser, but if you view the source you'll see this output:

<?php echo "hello world!"; ?>

This has to do with the way the browser is rendering your PHP code. Browsers aren't meant to render PHP code, but rather HTML markup. If you're echoing out the code because you're testing what is going to be written to your file, then just view the source to validate what is being output is what you want to be written to the file. You won't see it in the browser itself because it doesn't know how to render the ?php tag, let alone what to do with the echo attribute.

Optionally, like everyone has stated already you can pass the string through htmlspecialchars if all you want to do is render it in the browser without having to view source. You wouldn't want to do that if you're writing it to the file, but may help you debug your output.

Another option would be to run your script from the command line. It won't attempt to render your output and instead just spit it out verbatim.

Answer 7:

Eval php documentation

Use Eval() if you want to run the code in the string.

Example

$str = "Hello ";
eval('$str .= "World"');

echo $str;
/* Output: Hello World */

References