如何将变量保存到文件中

时间:2015-05-07 07:19:28

标签: php 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);
}

尝试将$post, $name$date的值分别放入post.txt,name.txt和date.txt文件中,但它将文字"$post"放入post.txt等等。请帮忙!

3 个答案:

答案 0 :(得分:1)

请使用数组,这是正确的选择。

$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);
}

答案 1 :(得分:1)

尝试使用variable of variable -

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

变量变量采用变量的值并将其视为变量的名称。

您将获得详细信息here

答案 2 :(得分:1)

您正在使用$ x =“$”。$ x,它不会为您提供所需的值。 试试这个:

$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);
}