简体   繁体   中英

How to save input form data as an array in PHP

I have a form which takes a student name, subject and age. When submitted, it saves the data as an array in txt file. Next time, when I put new data and submit it, it creates a new array in that txt file instead of appending it to the previous array.

<?php
if(!empty($_GET)){
    $student = [];
    $student['name'] = $_GET['name'];
    $student['subject'] = $_GET['subject'];
    $student['age'] = $_GET['age'];
    $studentArray = [];
    array_push($studentArray, $student);
    $str = print_r($studentArray, true);
    file_put_contents('student.txt', $str, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" method="GET">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">

        <label for="name">Subject:</label>
        <input type="text" name="subject" id="subject">

        <label for="name">Age:</label>
        <input type="number" name="age" id="age">

        <input type="submit" name="submitButton">
    </form>
</body>
</html>

output looks like this:

在此处输入图片说明

however I want to save it like below:

在此处输入图片说明

How could I do that?

If you really have to see your nice array in text use this:

    if(!empty($_GET)){
        $student = array();
        $int = 0;
        $txtfile = "student.txt";
        if (file_exists($txtfile)) {
            $fgc = file_get_contents($txtfile);
            $expl = explode("[".$int."] => Array", $fgc);
            while (count($expl) > 1) {
                $expl2 = (count($expl) > 1) ?  explode("[".($int+1)."] => Array", $expl[1])[0] : $expl[1];
                $m = preg_match_all("@\\[([\d\w]+)\\] => ([^\n]*)@imus", $expl2, $matches);
                if ($m == 0) { break; }
                foreach ($matches[1] as $key => $val) {
                    $student[$int][$val] = $matches[2][$key];
                }
                $int++;
                $expl = explode("[".$int."] => Array", $fgc);
            }
        }
        $student[$int]['name'] = $_GET['name'];
        $student[$int]['subject'] = $_GET['subject'];
        $student[$int]['age'] = $_GET['age'];
        $str = print_r($student, true);
        file_put_contents('student.txt', $str);

        print_r($student);
    }

But please use a serialized version like this:

    if(!empty($_GET)){
        $student = array();
        $int = 0;
        $txtfile = "student.txt";
        if (file_exists($txtfile)) {
            $fgc = file_get_contents($txtfile);
            $student = unserialize($fgc);
            $int = count($student);
        }
        $student[$int]['name'] = $_GET['name'];
        $student[$int]['subject'] = $_GET['subject'];
        $student[$int]['age'] = $_GET['age'];
        file_put_contents('student.txt', serialize($student));

        print_r($student);
    }

print_r for debug only.

Have fun ;)

You have to use JSON in order to update your array constantly. the important point is you have to load your students in a variable and then push the new student to that variable so, in the end, you can save your students variable which contains all students in one array like you want.

Requirements to make this code works:

  1. Create a file named student.json and put [] inside the file

Also, I highly suggest go and learn about JSON in PHP so you can have a better understanding of how this code is working now

if(!empty($_GET)){
    $student = [];
    $student['name'] = $_GET['name'];
    $student['subject'] = $_GET['subject'];
    $student['age'] = $_GET['age'];
    $studentArray = json_decode( file_get_contents('student.json'), true);
    array_push($studentArray, $student);
    $str = print_r($studentArray, true);
    file_put_contents('student.json', json_encode($studentArray));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM