You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中通过head.php包含文件,解决字符串替换后代码未执行问题

问题解决方法

核心原因

file_get_contents()仅读取文件的原始文本内容,不会解析执行其中的PHP代码,所以你得到的是<?php include "analytic.php"; ?>字符串,而非代码执行后的最终HTML结果。

修正后的index.php代码

要获取head.php执行后的输出内容,需通过输出缓冲捕获执行结果:

$head = " <head> </head>";
// 开启输出缓冲,暂存后续输出内容
ob_start();
// 执行head.php,其中的PHP代码会被解析运行
include 'head.php';
// 获取缓冲中的执行结果并关闭缓冲
$headin = ob_get_clean();
// 执行字符串替换
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head; 

代码说明

  • ob_start():开启输出缓冲,后续所有输出(包括PHP执行后的HTML)都会被暂存,不会直接输出到浏览器。
  • include 'head.php':执行head.php文件,其中的include "analytic.php"会被解析执行,最终生成<title> Hello world </title>,该内容会被缓冲捕获。
  • ob_get_clean():提取缓冲中的执行结果,同时清空并关闭缓冲,此时$headin即为head.php执行后的最终HTML内容。
  • 后续的字符串替换和echo操作,就能得到你期望的输出结果。

最终输出验证

执行修正后的代码,输出结果为:

<head><title> Hello world </title> </head>

内容的提问来源于stack exchange,提问作者Mehul Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:01:25