如何获取php文件中html生成的内容,而不是包含该文件


How to get the html generated contents of a php file instead of include the file

我想制作一个cms,它生成html页面并创建文件来存储每个页面。

理想情况下,我需要这样的东西:

<?php
$file1 = get_produced_html_from('mainPage.php');
/* write the file to a directory*/

$file2 = get_produced_html_from('ProductsPage.php');
/* write the file to a directory*/
?>

除了require、include、require_one、include_ose等,我有没有遗漏任何函数?

澄清一下:我不需要php文件中的php代码。我只需要html内容,这意味着php文件应该首先执行。

你认为解决方案是使用http://php.net/manual/en/function.file-get-contents.php通过阅读http://domain.com/templates/mainPage.php作为html流?

非常感谢。

您需要捕获缓冲区的输出。

下面是我为某人编写的一段代码,用于演示一个非常简单的视图渲染器类。

public function render($file) {
    $file = $this->viewPath = APP_ROOT . 'View' . DS . $file . '.php';
    if (is_file($file)) {
        ob_start();
        extract($this->_vars);
        include($file);
        $content = ob_get_contents();
        ob_end_clean();
    } else {
        throw new RuntimeException(sprintf('Cant find view file %s!', $file));
    }
    return $content;
}

它打开输出缓冲区(ob_start())执行php文件并设置变量,然后获取缓冲区(ob_get_contents()),然后为下一个操作(ob_end_clean())清理缓冲区。您也可以使用ob_end_flush()直接清理和发送缓冲区。我不会这么做,而是对应用程序进行适当的关闭过程,并确保在将页面发送到客户端之前,一切都做得很好,没有错误。

我想我很快就会在Github上提供整个代码。然后我会更新答案。

您只需使用cURL就可以从url中获得整个渲染输出。

你可以这样使用它:

// Initiate the curl session
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/mypage.php');
// Allow the headers
curl_setopt($ch, CURLOPT_HEADER, true);
// Return the output instead of displaying it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the curl session
$output = curl_exec($ch);
// Close the curl session
curl_close($ch);
相关文章: