dongyongan9941 2012-05-30 14:55
浏览 20
已采纳

如何 - 如果满足条件,则将选择写入文件

I have the following PHP code that checks which choice from a radio button was selected and then write to a file of the same name.

For example, from a Radio button group called "instrument", where the 4 choices are

  1. Wind
  2. Strings
  3. Percussion
  4. Vocal

If the user selects "Wind", then it would create and write to a file called "wind_instrument.txt". If "strings" is selected it would create the file "string_instrument.txt" and so on.

Here is my PHP code:

if ($_POST['instrument'] == "wind")
{


$lines = file('wind_instrument.txt');
$fopen = fopen("wind_instrument.txt", "w+");

}

elseif ($_POST['instrument'] == "strings")
{

$lines = file('strings_instrument.txt');
$fopen = fopen("strings_instrument.txt", "w+");

}

elseif ($_POST['instrument'] == "percussion")
{

$lines = file('percussion_instrument.txt');
$fopen = fopen("percussion_instrument.txt", "w+");

}

elseif ($_POST['instrument'] == "vocal")
{

$lines = file('vocal_instrument.txt');
$fopen = fopen("vocal_instrument.txt", "w+");

}

Now, if one of the conditions is met, would then go on to the next step in my code, being:

fwrite($fopen, ("Instrument: ")."");
fwrite($fopen, $_POST["instrument"]."
");
fwrite($fopen, ("<br>")."
");

The problem I have with this, is that it is not creating a file, and I do have permissions set.

Any help will be greatly appreciated, thank you.

  • 写回答

2条回答 默认 最新

  • duandang6111 2012-05-30 15:12
    关注

    You actually could do some refactoring in order to make it easier to maintain, nevertheless that wasn't your problem but I shall try to help you out.

    <?php
      $instruments = array('wind', 'strings', 'percussion', 'vocal');
    
      if (in_array($_POST['instrument'], $instruments))
      {
        $instrument = $_POST['instrument'];
        $file_handle = fopen($instrument.'_instrument.txt', 'a+');
        $line = 'Instrument: '.$instrument."
    ";
        fwrite($file_handle, $line);
      }
    ?>
    

    The important thing to know is how I open the file. I use the mode a+. The documentation says

    Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

    Hope that helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助