php - 修改内容后如何包含存储在变量中的 PHP 文件的内容?
问题描述
我有一个 PHP 模板文件, index.php
其中包含 PHP 和 HTML
如果我include 'index.php';
是文件,一切都会按预期工作。
但我想在包含它之前修改文件,为此我编写了以下代码:
$contents = file_get_contents('index.php');
// The position at which the HTML <head> tag ends in index.php
$posHeadEnd = strpos($contents, '</head>');
$linkTag = "<link rel='stylesheet' href='/assets/css/main.css' type='text/css'>";
// Insert <link> tag into the contents
$contents = substr($contents, 0, $posHeadEnd) . $link . substr($contents, $posHeadEnd);
include $contents;
此函数<link>
向变量添加标签以$contents
添加额外的 CSS。
完成后,它包含$contents
变量。
我不明白error_log
文件中的错误:
PHP Warning: include(<?php
$locale = $this->Template->locale;
?>
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta property="og:title" content="eDiary"/>
<title>eDiary</title>
[01-May-2021 15:24:50 Europe/Copenhagen] PHP Warning: include(): Failed opening '<?php
$locale = $this->Template->locale;
?>
<!DOCTYPE html>
该错误似乎是index.php
HTML 字符编码的内容。
我尝试过使用该html_entity_decode
功能,但没有帮助。
也许这是include
函数中的一个问题,或者它不打算以这种方式使用?
解决方案
include
在这里包含文件。您不能包含字符串。您的脚本尝试包含一个名称为 index.php 的文件,这就是警告的内容:
PHP 警告:include(): 未能打开 '<?php...
不确定您到底想要实现什么,但可能您应该<link>
在 index.php 中添加该附加标签。可能在条件内。就像是
$needsLinkTag = true;
include index.php
在 index.php 里面
...
if ($needsLinkTag) {
echo '<link ...';
}
推荐阅读
- c# - c#在选择列表框中的另一个项目之前要求保存更改
- javascript - 使用 chromedp,从 *runtime.RemoteObject 中获取一个 javascript 对象/数组
- visual-studio-code - 跨文件的 Visual Studio Code 搜索(在文件中查找)不起作用
- javascript - Axios Vue.js 将对象数组从 store.js 传递给组件
- json - Groovy:将 XML 嵌套到 Json
- json - 如何从消息头中获取我的主题名称并发布
- c# - 除非 Mysql 数据库处于联机状态,否则 C# 程序不会启动
- javascript - Angular查找控件名称所属的嵌套组
- java - Microsoft Project Online SDK API/REST API 支持
- python - Python:如何导入带有控制字符分隔符的 csv 类 dat 文件