修改变量后如何包含存储在变量中的PHP文件的内容';什么内容?
我有一个PHP模板文件,修改变量后如何包含存储在变量中的PHP文件的内容';什么内容?,php,Php,我有一个PHP模板文件,index.PHP,其中包含PHP和HTML 如果我包含'index.php'文件,一切正常 但我想在包含该文件之前对其进行修改,为此,我编写了以下代码: $contents = file_get_contents('index.php'); // The position at which the HTML <head> tag ends in index.php $posHeadEnd = strpos($contents, '</head>
index.PHP
,其中包含PHP和HTML
如果我包含'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;
错误似乎是index.php
的内容,但编码了HTML字符
我尝试过使用html\u entity\u decode
函数,但没有帮助
这可能是include
函数中的一个问题,也可能不是这样使用的?include
用于包含文件。不能包含字符串。您的脚本试图包含一个名为index.php的文件,警告是这样说的:
PHP警告:include():无法打开“用此代码替换代码
$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';
$contents=file_get_contents('index.php');
//HTML标记在index.php中结束的位置
$posHeadEnd=strpos($contents',);
$linkTag=“”;
//在内容中插入标签
$contents=substr($contents,0,$posHeadEnd)$链接substr($contents,$posHeadEnd);
文件内容('index.php',$contents,LOCK_EX);
包括'index.php';
PHP函数用于将单独的PHP文件加载到文件中,它的参数应该是要包含的PHP文件的路径,而不是HTML字符串。我建议您阅读一下include的作用,您会发现最好包含index.php,然后从该文件中回显一些内容。只需回显$contents
,看起来您正试图将其用作模板。如果内容只是HTML,则可以回显/打印内容。如果您确实需要解析php代码,您可能需要考虑另一种方式。但请注意,这将永久更改index.php
的内容。也许不是你们想要的……是的,我同意你们的观点,但问题询问者并没有提到他是否需要永久性改变或临时改变。。。。另一个解决方案是,他可以将自己代码中的最后一行从“include$contents;”替换为“echo$contents;”
$needsLinkTag = true;
include 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';