Search code examples
phpstringescapingnowdoc

escaping "<?php" and "?>" when outputing to a file - nowdoc/heredoc


What I was trying to do (and could, actually but only on my local testserver) is to output a php-file with php.
The problem seems to be the opening and closing tags of php.
I looked up nowdoc in php.net but could not find a clue to the solution. If I use it like this:

$fh = fopen($filenameandpath, 'w') or die("can't open file");
$stringData = <<<'WWR'
<?php
echo('test');
?>
WWR;
$suc = fwrite($fh, $stringData);
fclose($fh);

I get a parsing error:

Parse error: syntax error, unexpected T_SL in /home/ua000154/public_html/test.php on line XX

The linenumber of this parsing error is always where the opening php-tag is found. My problem seems to be that I need to escape this tag (I presume I should do the same with the closing tag)

How could I do this? This actually worked on my test server but would not once I uploaded it to the final location on another server.

Any help is apreciated. Thanks you for your time!


Solution

  • If you're intentionally using NOWDOC syntax, make sure your PHP server is running 5.3 or later, since that was when it was introduced. (You can check using phpinfo();). That would explain why it worked on your dev server but not on production.