phpescapingheredocnowdoc

Interpreting variables but ignoring escape sequences in PHP HEREDOC


I am trying to figure out how I can use HEREDOC syntax to interpret variables but ignore the backslash character. Or use NOWDOC syntax to allow for the interpretation of variables. An example of what I am trying to do:

$title = "My title here";
$date = "Aug 12, 2017";

$latex_code = <<<LCODE
    \documentclass{article}

    \usepackage{graphicx}

    \pagestyle{head}
    \firstpageheader{
        $title
        $date
     }
LCODE;

file_put_contents("article.tex", $latex_code);

I want to ignore all slashes but interpret the variables $title and $date. Is there a way to do this without exiting from a HEREDOC or NOWDOC block?


Solution

  • At the risk of misunderstanding the intended output, I think you could just escape the backslashes. (I'm assuming you want the single backslashes included in the output.)

    $title = "My title here";
    $date = "Aug 12, 2017";
    
    $latex_code = <<<LCODE
        \\documentclass{article}
    
        \\usepackage{graphicx}
    
        \\pagestyle{head}
        \\firstpageheader{
            $title
            $date
         }
    LCODE;
    

    Obviously if you don't do that, some of them (e.g. \f) will be escape sequences that will be interpreted.