首页 > 解决方案 > 修改内容后如何包含存储在变量中的 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(&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.phpHTML 字符编码的内容。

我尝试过使用该html_entity_decode功能,但没有帮助。

也许这是include函数中的一个问题,或者它不打算以这种方式使用?

标签: php

解决方案


include在这里包含文件。您不能包含字符串。您的脚本尝试包含一个名称为 index.php 的文件,这就是警告的内容:

PHP 警告:include(): 未能打开 '<?php...

不确定您到底想要实现什么,但可能您应该<link>在 index.php 中添加该附加标签。可能在条件内。就像是

$needsLinkTag = true;

include index.php

在 index.php 里面

...
if ($needsLinkTag) {
  echo '<link ...';
}

推荐阅读