0

I can return a value from embedded php within the variable (as below), but in this case I would like to get the output of a php file e.g. result.php.

var jsVar = "<?php echo 'thisisfromphp' ?>";

So running 'result.php' would produce a result to be returned. How could I grab this result from result.php and use it as the variable - I was thinking something like:

var jsVar = "<?php echo result.php ?>";

P.S. I would embed the php code from result.php in the variable (as above) but it all gets to messy..

Mike
  • 2,266
  • 10
  • 29
  • 37

1 Answers1

2

What you should do is refactor your code. Don't have result.php echo something out that you try and capture. That's not resuable code. Abstract whatever it does into a function that can be reused, then you can just require "result.php" and later callYourFunction() to get the desired output.

If, however, you are insistent on doing it this way (which, again, I advise against), you could:

ob_start();
require_once 'result.php';
$contents = ob_get_contents();
ob_end_clean();

// later...
var jsVar = <?php echo json_encode($contents); ?>
Colin M
  • 13,010
  • 3
  • 38
  • 58