簡體   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