本文介绍如何在 php 中正确包含并执行一个包含 php 代码(如 `include` 语句)的文件,使其输出被真实解析而非原样输出,适用于需在字符串替换流程中嵌入动态生成 html 的场景。
在实际开发中,有时需要将 PHP 文件(如 head.php)的内容作为字符串读取后,注入到另一段 HTML 字符串中(例如通过 str_replace 插入
标签内),但直接使用 file_get_contents() 仅会返回原始 PHP 源码文本,而不会执行其中的 include、echo 等逻辑——这正是你遇到的问题: 而非预期的根本原因在于:file_get_contents() 是纯文件读取函数,它不触发 PHP 解析器执行;而 include 语句只有在 PHP 运行时环境中才会被解释执行。
✅ 正确解法是:读取文件内容 → 在隔离的输出缓冲区中安全执行 → 捕获其真实输出。推荐使用如下封装函数:
function getEvaluatedContent($filePath) {
if (!is_file($filePath) || !is_readable($filePath)) {
throw new InvalidArgumentException("Cannot read file: {$filePath}");
}
$content = file_get_contents($filePath);
ob_start();
// 使用 '?>' 关闭当前 PHP 模式,使后续内容按 PHP 代码执行
eval('?>' . $content);
$output = ob_get_clean();
return $output;
}然后在 index.php 中调用:
$head = " "; $headin= getEvaluatedContent('head.php'); // ✅ 执行 head.php 并捕获其输出 $head = str_replace("", "" . $headin, $head); echo $head; // 输出:
Hello world
⚠️ 重要注意事项:
- eval() 存在安全风险,请仅用于可信的本地文件(如项目内固定的 head.php),切勿对用户输入或不可信路径使用;
- 确保 head.php 中无 '.$content) 可能引发解析错误;
- 更健壮的替代方案(推荐生产环境):改用 include 配合输出缓冲(ob_start() + include),避免 eval:
function getIncludedContent($filePath) {
if (!is_file($filePath) || !is_readable($filePath)) {
return '';
}
ob_start();
include $filePath;
return ob_get_clean();
}该方式更安全、语义清晰,且完全兼容常规 PHP 包含逻辑(支持变量传递、作用域继承等),是本场景下的最佳实践。
总结:不要用 file_get_contents() 直接拼接 PHP 文件——要执行,就得让 PHP 引擎真正运行它。借助输出缓冲 + include 或谨慎使用 eval,即可在字符串处理流程中无缝集成动态 PHP 输出。









