PyRoss
PyRoss

Reputation: 129

How to save variables to a file

$files = array("post", "name", "date");

$post = $_POST["comment"];
$name = $_POST["name"];
$date = date("H:i F j");

foreach ($files as $x) {
    $file = fopen("db/$x.txt", "a");
    $x = "$" . $x;
    fwrite($file, $x);
    fclose($file);
}

Trying to put values of $post, $name and $date into post.txt, name.txt and date.txt files respectively, but it puts literals "$post" into post.txt and so forth. Please help!

Upvotes: 1

Views: 78

Answers (3)

Richard Mosher
Richard Mosher

Reputation: 67

You are using $x = "$".$x which doesn't give you the values you want. Try this instead:

$files = [
    'comment' => $_POST['comment'],
    'name' => $_POST['name'],
    'date' => date('H:i F j')
];

foreach($files as $name => $value) {
    $file = fopen("db/$name.txt", "a");
    fwrite($file,$value);
}

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Try with variable of variable -

foreach ($files as $x) {
    $file = fopen("db/$x.txt", "a");
    $x = $$x;
    fwrite($file, $x);
    fclose($file);
}

A variable variable takes the value of a variable and treats that as the name of a variable.

You will get the details here

Upvotes: 1

pavel
pavel

Reputation: 27092

Use array instead, it's the right choice.

$values = array(
    'comment' => $_POST["comment"],
    'name' => $_POST["name"],
    'date' => date("H:i F j")
);

foreach ($values as $x) {
    $file = fopen("db/$x.txt", "a");
    fwrite($file, $x);
    fclose($file);
}

Upvotes: 1

Related Questions