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

2022-08-31 00:14:10

让我们假设我有以下文件 - :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>

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

我已经成功地使用cURL来访问文件的渲染版本,但它似乎相当缓慢和笨拙,为页面的执行增加了相当多的时间 - 我想这是由于正在执行DNS查找。

那么,我如何将 的内容放入字符串中 - 同时在那里有可用的PHP?template.php


答案 1

这应该这样做:

ob_start();
include('template.php');
$returned = ob_get_contents();
ob_end_clean();

答案 2

如果你不需要在PHP执行此操作,你可以从命令行执行一个php脚本,并将其通过管道传输到文本文件,如下所示:

php -f phpFile.php > output.html

推荐