user1481563
user1481563

Reputation: 125

Writing a variable to file PHP

When I execute this:

$filename = "test.php";
$content = "<?php $variable = 35 ?>";
file_put_contents($filename,$content);

The file contains this:

<?php  =35?>

How can I get it to include the $variable ?

Also, how can I append this to the top of the file without overwriting existing data?

Upvotes: 1

Views: 193

Answers (1)

nickb
nickb

Reputation: 59699

Use single quotes to prevent PHP from trying to interpolate $variable.

$content = '<?php $variable = 35 ?>';

Finally, you would append this to the file by using fopen() and passing the 'a' mode, which will append to the bottom of the file

To append to the top, it is a bit more complicated. As far as I know, you will have to read the entire file in and concatenate the old contents to the end of the new contents.

Upvotes: 5

Related Questions