Chris Bier
Chris Bier

Reputation: 14437

Putting PHP code in a string

How do I put PHP Code into a string?

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

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

Am I missing something? Is there a better or more proper way to do this? I am currently looking at the PHP docs on strings but I would like to get your feedback.

Edit: The reason why I am using apsotrophes (') and not quotes (") is because I don't want the code to fill in the value for condition. I want it to echo as-is.

Upvotes: 13

Views: 25667

Answers (7)

John Conde
John Conde

Reputation: 219794

Use htmlspecialchars():

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

Upvotes: 12

Jeff Lambert
Jeff Lambert

Reputation: 24661

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.

Upvotes: 0

Subodh Ghulaxe
Subodh Ghulaxe

Reputation: 18651

You can output PHP code as text in following way

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

Upvotes: 0

S.Visser
S.Visser

Reputation: 4725

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 */

Upvotes: -1

SidOfc
SidOfc

Reputation: 4584

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

Upvotes: 0

Mercurial
Mercurial

Reputation: 3885

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

Upvotes: 1

Adder
Adder

Reputation: 5868

You need to echo htmlspecialchars($phpCode);

Upvotes: 6

Related Questions