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!
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.
Ok, so this is an old question that has been answered, however this may be of use for anyone who wants to implement a similar concept to NOWDOC in earlier versions of php. it uses output buffering to capture text verbatim from the source file, without any variable parsing etc. ie not a lot of use if you WANT to insert variables, but you can literally put anything in it, as long as it does not include the characters "?>", which terminates it.
note that it differs from HEREDOC and NOWDOC that used >>>TERMINATOR and >>>'TERMINATOR' in that the variable is defined after the document.
<?PHP
function NOWDOC_() {
ob_start();
}
function _NOWDOC(&$buf=false) {
$buf_ = ob_get_contents();
ob_end_clean();
if ($buf!==false) $buf .= $buf_;
return $buf_;
}
NOWDOC_(); ?>random garbage, not shown, but captured into $myvar
it has all sorts ] [* \%& of characters in it
and completely ignores things like {$this} or $_SERVER['REMOTE_ADDR';
<?PHP _NOWDOC($myvar);
NOWDOC_(); ?><HTML><HEAD></HEAD>
<BODY>Here is some <B>nice</B> HTML & .
<SCRIPT>
alert("javascript!");
</SCRIPT>
this also demonstrates using $var = _NOWDOC() syntax.
</BODY>
</HTML><?PHP $myhtml = _NOWDOC();
echo "the html will be [".$myhtml."]";
?>
精彩评论