解析PHP页面并将HTML插入变量中


Parse PHP page and insert HTML into variable

在PHP中有这样的模板文件吗:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>sdfds</title>
</head>
<body>
    <div class="some-content">
        <?php some_content(); ?>
    </div>
</body>
</html>

并将其加载到变量中,而不回显,但仍解析some_content()的结果。假设some_content()响应<p>oh yes!</p>,那么这需要是变量中内容的一部分。这之所以重要,是因为我需要返回内容,而不是重复它。

我已经看过file_get_contents(),但它不会解析php,所以div为空。我需要parse_file_and_get_content()之类的东西。

是的,有了输出缓冲系统,这是可能的。

ob_start();
include("your_external_php_file.php");
$parsed_html = ob_get_clean();

include()将执行文件中的任何<?php ... ?>代码块,OB系统将在缓冲区处于活动状态时捕获该文件执行的任何输出。然后获取缓冲区的内容,现在$parsed_html已经拥有了所有的html,以及php函数调用输出的任何内容。