修改 PHP 文件的内容后,如何包含存储在变量中的 PHP 文件的内容?

  • 本文关键字:文件 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;

此函数向变量$contents添加一个<link>标记,以添加额外的CSS。

完成后,它包含$contents变量。

我不理解error_log文件中的错误:

PHP Warning:  include(&lt;?php
$locale = $this-&gt;Template-&gt;locale;
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;da&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;&gt;
&lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html;charset=UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;/&gt;
&lt;meta property=&quot;og:title&quot; content=&quot;eDiary&quot;/&gt;
&lt;title&gt;eDiary&lt;/title&gt;

[01-May-2021 15:24:50 Europe/Copenhagen] PHP Warning:  include(): Failed opening '&lt;?php
$locale = $this-&gt;Template-&gt;locale;
?&gt;
&lt;!DOCTYPE html&gt;

错误似乎是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';

最新更新