将数据输出到不同的.txt文件

时间:2013-08-22 17:20:33

标签: php html

我有一个html表单并使用get方法

如果用户选择鞋子选项值,我想将数据输入到shoes_sales.txt,并将所有其余内容输入到clothes_sales.txt。

我正在使用以下if语句

<?php
header("Location: thankforsumbitting.html");

if($_GET['variable1'] == "shoes" || $_GET['variable1'] == "shoes"){
  $handle = fopen("shoes_sales.txt", "a");
  foreach($_GET as $variable => $value) {
    fwrite($handle, $variable);
    fwrite($handle, "=");
    fwrite($handle, $value);
    fwrite($handle, "\r\n");
  }
  else {
    $handle = fopen("clothes_sales.txt", "a");
    foreach($_GET as $variable => $value) {
      fwrite($handle, $variable);
      fwrite($handle, "=");
      fwrite($handle, $value);
      fwrite($handle, "\r\n");
      fclose($handle);
      exit;
?> 

3 个答案:

答案 0 :(得分:0)

您忘记了}if条款以及第二个else的结束foreach

<?php
header("Location: thankforsumbitting.html");

if($_GET['variable1'] == "shoes" || $_GET['variable1'] == "shoes"){
    $handle = fopen("shoes_sales.txt", "a");
    foreach($_GET as $variable => $value) {
        fwrite($handle, $variable);
        fwrite($handle, "=");
        fwrite($handle, $value);
        fwrite($handle, "\r\n");
    }
    fclose($handle);
}
else {
    $handle = fopen("clothes_sales.txt", "a");
    foreach($_GET as $variable => $value) {
        fwrite($handle, $variable);
        fwrite($handle, "=");
        fwrite($handle, $value);
        fwrite($handle, "\r\n");
    }
    fclose($handle);
}
exit;
?> 

答案 1 :(得分:0)

丢失括号和逻辑问题

试试这个

<?php
  header("Location: thankforsumbitting.html");

  if ($_GET['variable1'] == "shoes") {
    $handle = fopen("shoes_sales.txt", "a");
  }
  else {
    $handle = fopen("clothes_sales.txt", "a");
  }
  foreach($_GET as $variable => $value) {
    fwrite($handle, $variable."=".$value."\r\n");
  }
  fclose($handle);
  exit;
?> 

答案 2 :(得分:0)

与其进行重复的 fwrite() 调用,为什么不构建格式化的文本,然后使用 file_put_contents() 仅写入一次到 txt 文件的末尾?这样可以减少函数调用。

代码:

$data = '';
foreach ($array as $key => $value) {
    $data .= "{$key}={$value}" . PHP_EOL;
}

file_put_contents(
    $_GET['variable1'] == "shoes" ? 'shoes_sales.txt' : 'clothes_sales.txt',
    $data,
    FILE_APPEND | LOCK_EX
);