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


Output data to different .txt files

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

如果用户选择了shoes选项值,我想将数据输入到shoes_sales.txt,并将其余数据输入到closs_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;
?> 

您忘记了ifelse子句的结束},以及第二个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;
?> 

丢失括号和逻辑问题

试试这个

<?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;
?> 

与其重复调用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
);