【问题标题】:PHP: file_get_contents a PHP file with include();PHP: file_get_contents 包含包含() 的 PHP 文件;
【发布时间】:2013-08-12 15:01:48
【问题描述】:

我有一个 PHP 脚本,它使用 file_get_contents 调用主 PHP 模板(充当 HTML 模板),从中替换几个单词,然后将最终文件另存为目录中的另一个 PHP。

但是主PHP模板本身有include();require_once();,替换单词后保存的文件不会加载从主模板调用的文件。

保存文件的 HTML 源代码中包含<?php include('file_here'); ?>,但没有包含 file_here 的输出 -- 见图片。

如何调用 file_get_contents();仍然让主模板执行 include();或 require_once(); ?

【问题讨论】:

  • 最好的办法是把主模板文件也包括在内,也许在 ob_start/ob_get_clean 块中,然后对结果进行替换。

标签: php include file-get-contents


【解决方案1】:

file_get_contents() 将获取文件的内容,而不是将其作为 PHP 脚本执行。如果您希望执行这段代码,您需要包含它或处理它(例如,通过对 Apache 的 HTTP 请求)。

如果您包含此文件,它将作为 PHP 代码处理,当然,打印您的 HTML 标记(include* 可以采用任何类型的文件)。

如果您需要在打印之前处理其内容,请使用ob_* 函数来操作 PHP 输出缓冲区。见:https://www.php.net/manual/en/ref.outcontrol.php

ob_start(); // Start output buffer capture.
include("yourtemplate.php"); // Include your template.
$output = ob_get_contents(); // This contains the output of yourtemplate.php
// Manipulate $output...
ob_end_clean(); // Clear the buffer.
echo $output; // Print everything.

顺便说一句,这样的机制对于模板引擎来说听起来很沉重。基本上,模板不应包含 PHP 代码。如果你想要这样的行为,看看 Twig :http://twig.sensiolabs.org/

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 2012-02-13
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多