我有一个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;
此函数向变量$contents
添加一个<link>
标记,以添加额外的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。。。
不确定你到底想实现什么,但可能你应该在index.php中添加额外的<link>
标记。可能在条件中。类似的东西
$needsLinkTag = true;
include index.php
和index.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';