Search code examples
phphtmlincludestr-replacefile-get-contents

How to include file in PHP with user defined variable


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


Solution

  • 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>