1

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?

5
  • I don't quite understand, why is the echo code the only one returned? are you only interested in returning echo calls? Commented Jul 10, 2016 at 9:02
  • 1
    ?>echo "hello there";<?php - drop out of PHP mode and anything you type (PHP code or otherwise) shows for the world to see. Commented Jul 10, 2016 at 9:02
  • seems like You want to get code of some encoded php file by executing between ob_* (: if Yes, so it's not done like this. Commented Jul 10, 2016 at 9:04
  • @num8er: if you say it's not done like this - can you elaborate how it is done? Commented Jul 10, 2016 at 9:45
  • I mean if You want to get source of obfuscated-encoded script, so You've to analyze file manually and do complex variable mapping and etc. I cannot show it's long procedure. Commented Jul 10, 2016 at 10:41

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

5 Comments

yes, but this kind of 'script' will be useless - you cant run it
It's actually useful if you have a script that needs to generate a hard-coded script ;)
Can you conditionally drop in and out of PHP?
Yes you can @Taapo just drop out in the body of an if/else statement
@TheH Problem with that approach is that you have to echo twice in an if/else statement, not? If you use <? if ($statement == true) { ?>echo "hello";<? } else { echo "hello"; } ?> -- I would love to prevent the double work. The following won't work, but I'm wondering if there is an other way? <? if ($statement == true) { ?> } echo "hello"; { <? } ?>
2

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. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";

result:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Comments

1

By representing it as a string:

ob_start();
$str = <<<STR
echo "hello there";
STR;
echo $str;
$output = ob_get_contents();
return $output;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.