-1

Using fwrite, I want to create a new php file that starts off with a variable. The new php file will use that variable to query sql and determine what content to load.

For example, the new php file that was created would start with $var=75

fwrite is confused by the $. I don't want fwrite to look at it as a variable, but instead print it as a text string. The new php file created will see it as a variable.

$myfile = fopen('test.php', 'w') or die('Unable to create new page');

    $txt="
        <?php $var=75 ?>
        <html>
        <body>
        Content here will be generated based on that sql row 75.
        </body>
        </html>
    ";

    fwrite($myfile, $txt);
    fclose($myfile);

I believe the $var is confusing it. fwrite wants to print it as the value of $var instead of the actual string "$var".

Please advise?

1 Answers1

0

Check What is the difference between single-quoted and double-quoted strings in PHP?

Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \ (So yes, even single quoted strings are parsed)

Use single quotes for $txt instead of double quotes.

Change to:

$myfile = fopen('test.php', 'w') or die('Unable to create new page');

$txt='
    <?php $var=75 ?>
    <html>
    <body>
    Content here will be generated based on that sql row 75.
    </body>
    </html>
    ';

fwrite($myfile, $txt);
fclose($myfile);
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57