1

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

10
  • file_get_contents only reads the file content, it does not put that content through the PHP parser. Commented Feb 6, 2023 at 9:44
  • Why not just do <head><?php include "head.php"; ?></head>? Please show me the detail if you can't. Commented Feb 6, 2023 at 9:47
  • @shingo analytic.php have analytic code from Google analytic, Microsoft clarity, and other analytic. head.php have many code including javascript and css linking. All are in different folder. So, i am trying to include all the analytic code in head.php and than head.php in index.php Commented Feb 6, 2023 at 9:50
  • @CBroe yes i know. even i cannot do $headin = include "analytic.php"; . What is the solution to it? Commented Feb 6, 2023 at 9:52
  • But that didn't explain why you cannot include head.php in index.php. Commented Feb 6, 2023 at 9:55

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.