Write PHP code in PHP

Viewed 14984

How can I write PHP code in PHP? I want to do this, but it doesn't work:

<?php echo '<?php echo \'aoeu\'; ?>'; ?>

Hope someone can give me a hint,

Many thanks

14 Answers

As a summary of many answers here you can echo o print php and html code by changing all special characters to its correspondent html special codes. Al least all '<' chars in string should be converted to '&lt'. There are many ways of doing this:

echo htmlspecialchars("<b>\"á'");
>> &lt;b&gt;&quot;á'

This converts all characters needed for echoing code.

echo htmlentities("<b>\"á'");
>> &lt;b&gt;&quot;&aacute;'

This does the same as htmlspecialchars but also converts all characters that have corresponding html codes.

Something worth noting is that single and double quotes have a different behavior as single quotes do not interpret variables inside them nor read escaped characters as such (except the single quote itself).

$foo = "value";

echo "I replace $foo with value and \n with line break";
>> I replace value with value and 
   with line break

echo 'I don\'t replace $foo with value nor \n with line break';
>> I don't replace $foo with value nor \n with line break

Also you could use heredoc syntax, that is equal as a double-quoted string but you don't need to escape them inside the string

echo <<<EOF
Your "string' here
EOF;

Or nowdoc syntax wich is the same but imitates a single-quoted string

echo <<<'EOF'
Your "string' here
EOF;

You can read all about these here: https://www.php.net/manual/es/language.types.string.php

Related