I have this code for example:
ob_start();
echo "hello there";
$output = ob_get_contents();
return $output;
When I run it, I get back:
hello there
But how can I get back
echo "hello there";
Is there a way to do this easily?
To output arbitrary text as-is you can close the PHP script and then reopen it. Anything between the closing and opening tags is output as-is
ob_start();
?>echo "hello there";
<?php
$output = ob_get_contents();
return $output;
ob_get_contents
will return the echoed output, so you can't use it to show actual code.
To simply print out code, I would try this:
$code = file_get_contents('your_code.php');
echo "<pre>{$code}</pre>";
Also you can write you code separatle as text and echo it or eval (if you need execution).
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "
";
eval("\$str = \"$str\";");
echo $str. "
";
result:
This is a $string with my $name in it.
This is a cup with my coffee in it.
By representing it as a string:
ob_start();
$str = <<<STR
echo "hello there";
STR;
echo $str;
$output = ob_get_contents();
return $output;