执行PHP文件,并将结果作为字符串返回

Evi*_*kie 14 php string

我们假设我有以下文件 - template.php:

<?php $string = 'Hello World!'; ?>
<html>
    <head>
        <title>Test Page!</title>
    </head>
    <body>
        <h1><?= $string; ?></h1>
        <p>You should see something above this line</p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我知道我可以用来file_get_contents()将文件的内容作为字符串获取,然后我可以根据需要进行操作.但是,file_get_contents()不执行PHP语句.

我已成功使用cURL来访问文件的渲染版本,但它看起来相当缓慢和笨重,为页面的执行添加了相当多的时间 - 我想这是由于正在执行DNS查找.

那么,我怎样才能将内容template.php转换为字符串 - 同时在那里使用PHP?

bis*_*sko 41

这应该这样做:

ob_start();
include('template.php');
$returned = ob_get_contents();
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)

  • 我想他要说的是要小心,如果你正在执行的php文件有任何副作用,它可能会改变应用程序的状态,即使它没有将输出发送到浏览器. (2认同)