1

I have tried searching for a way to escape php in a string and have been unsuccessful. I basically want to be able to write a string that contains php without php parsing it.

The error:

Undefined Variable

Code

$file = fopen("test.php", "w");
$content = "<?php echo $somevariable; ?>";
fwrite($file, $content);

*updated to show variable in string.

11
  • 6
    Use single quotes. Commented Sep 5, 2014 at 20:16
  • 2
    PHP will not execute embedded PHP. What you have will work exactly as you want: The characters <, ?, p etc... will get written out to the file. Commented Sep 5, 2014 at 20:17
  • Uhh what do you want? Your code looks fine. Commented Sep 5, 2014 at 20:17
  • 1
    Thanks for the replies, the single quotes seem to have done it. I didn't mention above that I had a variable in the string that was causing an undefined variable error. Commented Sep 5, 2014 at 20:20
  • 1
    @GergoErdosi: You should make that an answer :-D Commented Sep 5, 2014 at 20:22

1 Answer 1

4

Variables in double quotes are expanded:

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Use either single quotes:

$content = '<?php echo $somevariable; ?>';

or a nowdoc:

$content = <<<'EOD'
<?php echo $somevariable; ?>
EOD;

A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.