【问题标题】:How to get the html generated contents of a php file instead of include the file如何获取 php 文件的 html 生成内容而不是包含该文件
【发布时间】:2013-08-25 23:05:33
【问题描述】:

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

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

<?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_once、include_onse 等?

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

您是否认为解决方案类似于通过将http://domain.com/templates/mainPage.php 读取为html 流来使用http://php.net/manual/en/function.file-get-contents.php

非常感谢。

【问题讨论】:

  • fwritefile_put_contents 可以写入内容,如果您正在寻找的话。
  • 但是要从文件中获取内容,是的,您可以使用 file_get_contents 然后从变量中回显内容,或者您​​可以使用 CURL。
  • 我认为你们走错了路,伙计们。
  • @burzum 我想我当时可能误解了这个问题。你对 OP 有什么想法?
  • @Fred-ii-:我将其解读为,“我如何获得 mainPage.php 会生成的 HTML?”

标签: php html content-management-system


【解决方案1】:

您需要从缓冲区中捕获输出。

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

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 上提供整个代码。到时候我会更新答案。

【讨论】:

  • 看到cHao为我澄清的内容后,我就是这么想的。
  • 我实际上已经多次将类似的东西用于 PHP 模板。只要模板不修改任何内容,就可以很好地工作。
  • 模板不应该修改任何东西,除了查看相关数据。但是您可以使用相同的代码,而不是执行包含,您可以使用像 Twig 这样的模板引擎,该脚本使用的是 include()。
【解决方案2】:

您可以只使用 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);

【讨论】:

  • file_get_contents('http://www.example.com/mypage.php') 的主要优点是,如果 allow_url_fopen 关闭,它可以工作。好吧,如果您觉得特别勇敢,您可以尝试发送会话 cookie 以获取用户看到的 URL。但不要那样做。或者至少,在尝试之前关闭脚本中的会话。
  • 不,它只是从另一个页面获取 html 内容,因此无需模拟用户。在现实生活场景中,我建议通过 json 调用将静态文件与数据库进行另一层交互,但这是另一个故事!
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 2019-12-30
  • 2019-08-25
  • 2011-11-30
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多