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