1

I have a PHP file paypal.php.

<script src="https://www.paypal.com/sdk/js?client-id=<?php echo get_paypal('client-id'); ?>&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script>
<script>
paypal.Buttons({
    // ...
}).render('#paypal-button-container-<?php echo get_paypal('plan-id'); ?>');

I want to evaluate paypal.php in another php file and store the evaluation result in a variable and then output it to the user at later time.

Using this approach

$content = eval('?>' . file_get_contents('paypal.php') . '<?php');

the script tag is being echo-ed and the javascript is executed in the browser. But I do not want it to be echo-ed. I just want to keep the result for further processing.

How can I avoid echo-ing the evaluation result and just store the result in a variable?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Abid
  • 565
  • 1
  • 5
  • 15
  • 3
    It's not clear what you actually mean. If you don't output the JS code to the browser, it cannot be executed. Are you saying you just want to get the raw contents of `paypal.php` as a string in PHP? – ADyson Aug 13 '23 at 20:30
  • 2
    I don't understand what you're getting at. You have a PHP file that contains only JavaScript. PHP won't run that, so when you execute `file_get_contents()` it will just send the raw JavaScript. PHP is executed on the server, while JavaScript is executed in the browser. You can't mix the two. – Tangentially Perpendicular Aug 13 '23 at 20:44
  • Probably related: https://stackoverflow.com/q/13840429/14853083 – Tangentially Perpendicular Aug 13 '23 at 20:45
  • I do not want to get the raw content. This can be done by just using file_get_contents. I want to get the code after being evaluated by the php interpreter. – Abid Aug 13 '23 at 20:45
  • 1
    eval() doesn't return a value (unless the script it's executing contains a `return`) - this is clear in the [documentation](https://www.php.net/manual/en/function.eval.php). So it's just executing the code and it's outputting as usual. It's not storing it in $content. That's the reason your code isn't doing what you wanted. Output buffering, as per [the answer below](https://stackoverflow.com/a/76895148/5947043) is a reasonable solution. – ADyson Aug 13 '23 at 22:46

1 Answers1

3

To store some content in a PHP variable before it's displayed, you can use PHP buffering functions ob_start() and ob_get_clean() as follows:

<?php 
    ob_start(); // Start buffering 
?>
<script src="https://www.paypal.com/sdk/js?client-id=<?php echo get_paypal('client-id'); ?>&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script>
<script>
paypal.Buttons({
    // ...
}).render('#paypal-button-container-<?php echo get_paypal('plan-id'); ?>');
<?php 
// We can now store the buffered content in a variable
$buffered_content = ob_get_clean(); 
?>
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399