如何从复选框写入文本文件


How to write to textfile from checkboxes?

我在写入文本文件时遇到问题。用户单击表单中一个或多个复选框的值。完成后,应将其打印到文本文件中。因此,如果用户标记肉和苹果,它应该将其打印到文本文件shoppingcart.txt中

我对html、css和php非常陌生。代码低于我目前所取得的成绩。

<article class="article">
<p>What in the store and their prices</p>
<?php

foreach($file as $line) {
echo $line;
}
?>
<p> Below you can order some things!</p>

<form method="post" action="">
<input type="checkbox" name="cb" value="meat"<br>
<input type="checkbox" name="cb" value="apple"<br>
<input type="checkbox" name="cb" value="drinks"<br>
<input type="submit" value="Submit">

<?php
$myfile = fopen("shoppingcart.txt", "w") or die("Unable to open file");
fwrite($myfile
?>
</form>

我应该在表单下面的php部分写些什么?

index.html:

<form method="post" action="index.php">
            <input type="hidden" name="id" value="123" >
     Meat:  <input type="checkbox" name="cb[]" value="meat"><br/> // name is cb[] , not cb
     Apple: <input type="checkbox" name="cb[]" value="apple"><br/>
     Drinks:<input type="checkbox" name="cb[]" value="drinks"><br/>
            <input type="submit" value="Submit">
</form>

index.php:

<?php
$cb_v = isset($_POST['cb']) ? implode(',', $_POST['cb']) . PHP_EOL : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
 if ($cb_v && $id) {
    file_put_contents("/tmp/shoppingcart{$id}.txt", $cb_v, FILE_APPEND | LOCK_EX);
 }

这里是一个非常基本的工作示例。您可以将其作为添加更多有趣功能的开始:)

<article class="article">
    <p>What in the store and their prices</p>
    <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $result_string = '';
            foreach($_POST as $item) {
                $result_string .= $item."'n";
            }            
            file_put_contents('shoppingcart.txt', $result_string , FILE_APPEND | LOCK_EX);
        }
    ?>
    <p> Below you can order some things!</p>
    <form method="post" action="">
        <input type="checkbox" name="meat" value="meat"<br>
        <input type="checkbox" name="apple" value="apple"<br>
        <input type="checkbox" name="drinks" value="drinks"<br>
        <input type="submit" value="Submit">
    </form>
</article>