[英]How can I include the contents of a PHP file stored in a variable after modifying it's content?
我有一个 PHP 模板文件index.php
,它同时具有 PHP 和 Z4C4AD5FCA2007A3F74ZDBB1 initC
如果我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;
此 function 将<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
function 但这没有帮助。
也许这是include
function 中的问题,或者它不打算以这种方式使用?
include
在这里包含文件。 您不能包含字符串。 您的脚本尝试包含一个名称为 index.php 的文件,这就是警告的内容:
PHP 警告:include():打开失败'<?php ...
不确定您到底想要实现什么,但可能您应该在 index.php 中添加额外的<link>
标记。 可能在条件内。 就像是
$needsLinkTag = true;
include index.php
和内部索引.php
...
if ($needsLinkTag) {
echo '<link ...';
}
用此代码替换您的代码。
$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);
file_put_contents('index.php', $contents, LOCK_EX);
include 'index.php';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.