英文:
How to include file in PHP with user defined variable
问题
我试图在字符串替换中包含文件,但在输出中得到的是字符串而不是最终输出。
analytic.php
<?php echo "<title> Hello world </title>"; ?>
head.php
<?php include "analytic.php"; ?>
index.php
string = " <head> </head>";
$headin = file_get_contents('head.php');
$head = str_replace('"<head>"', '"<head>"'. $headin, $head);
echo $head;
我得到的输出 :
<head><?php include "analytic.php"; ?> </head>
我需要的输出 :
<head><title> Hello world </title> </head>
注意 : 请不要建议在index.php
中直接使用analytic.php
,因为head.php
中包含一些重要的代码,必须将analytic.php
与head.php
合并,然后在index.php
中使用。
英文:
I am trying to include file in string replace but in output i am getting string not the final output.
analytic.php
<?php echo "<title> Hello world </title>"; ?>
head.php
<?php include "analytic.php"; ?>
index.php
string = " <head> </head>";
$headin = file_get_contents('head.php');
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output i am getting :
<head><?php include "analytic.php"; ?> </head>
Output i need :
<head><title> Hello world </title> </head>
Note : Please do not recommend using analytic.php
directly in index.php
because head.php
have some important code and it has to be merged analytic.php
with head.php
and then index.php
答案1
得分: 2
要获得所需的输出:
function getEvaluatedContent($include_files) {
$content = file_get_contents($include_files);
ob_start();
eval("?>$content");
$evaluatedContent = ob_get_contents();
ob_end_clean();
return $evaluatedContent;
}
$headin = getEvaluatedContent('head.php');
$string = "<head> </head>";
$head = str_replace("<head>", "<head>" . $headin, $head);
echo $head;
输出将是output string
而不是file string
:
<head><title> Hello world </title> </head>
英文:
To get the desired output :
function getEvaluatedContent($include_files) {
$content = file_get_contents($include_files);
ob_start();
eval("?>$content");
$evaluatedContent = ob_get_contents();
ob_end_clean();
return $evaluatedContent;
}
$headin = getEvaluatedContent('head.php');
string = " <head> </head>";
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output will be output string
not file string
:
<head><title> Hello world </title> </head>
答案2
得分: 1
$file = file('绝对/路径/到/文件.php');
foreach ($file as $line => $code) {
if (str_contains($code, '<head>')) {
$file[$line] = str_replace('<head>', '<head>' . $headin, $code);
break;
}
}
file_put_contents('绝对/路径/到/文件.php', $file);
英文:
I think your approach is pretty basic (you try to hardcore modify - programmerly edit - the template script, right?) but anyway:
$file = file('absolut/path/to/file.php');
foreach ($file as $line => $code) {
if (str_contains($code, '<head>')) {
$file[$line] = str_replace('<head>', '<head>' . $headin, $code);
break;
}
}
file_put_contents('absolut/path/to/file.php', $file);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论