Search code examples
phpfileheredoc

How to expand variables that are in a text file when reading the file into a string?


In the context of processing html form input and responding by sending email via php, rather than having a lengthy heredoc assignment statement in the middle of my code, I'd like to have the email text in a file and read it in when needed, expanding the embedded variables as required.

Using appropriately prepared HTML form data input, I previously had…

$message = <<<TEXT  
NAME: {$_POST["fname"]} {$_POST["lname"]}
POSTAL ADDRESS: {$_POST["postal"]}
EMAIL ADDRESS: {$_POST["email"]}
[... message body etc.]
TEXT;

Moving the text to a file I then tried…

$message = file_get_contents('filename.txt');

…but found that variables in the text are not expanded, resulting in output including the variable identifiers as literals.

Is there a way to expand the variables when reading the file into a string ?


Solution

  • There's probably a duplicate, if found I'll delete. But there are two ways that come to mind:

    If you construct your file like this:

    NAME: {fname} {lname}
    

    Then loop the $_POST variables:

    $message = file_get_contents('filename.txt');
    
    foreach($_POST as $key => $val) {
        $message = str_replace('{'.$key.'}', $val, $message);
    }
    

    If you construct your file like this:

    NAME: <?= $_POST["fname"] ?> <?= $_POST["lname"] ?>
    

    If HTML .txt or other (not .php) then:

    ob_start();
    $file = file_get_contents('filename.txt');
    eval($file);
    $message = ob_get_clean();
    

    If it's a .php file then buffer the output and include:

    ob_start();
    include('filename.php');
    $message = ob_get_clean();