繁体   English   中英

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

[英]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(&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 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM