prado prado - 4 months ago 15
HTML Question

how to store $_POST values to save in a file line by line

I have a PHP form and I want to save the selected values to a file one in a line. I am not very much used with PHP.

Right now, my script is storing data in one line with many other characters included. Below is the code I am using in the action.php

if(isset($_POST)) {
$o = json_encode($_POST);
file_put_contents('data.txt',$o);

die();
}


The output I am receiving in data.txt is like below.


{"formDoor":["phpandmysql.tk\r\n","mytestdomainjordi\r\n","my1domain\r\n","ihatelinux\r\n","php1andmysql.tk\r\n","lubitz.co\r\n","testereed.com\r\n"],"formSubmit":"Submit"}


What I would like to get is something like this:

phpandmysql.tk
mytestdomainjordi
my1domain
ihatelinux
php1andmysql.tk
lubitz.co
testereed.com


EDIT

FORM:

<?php
$handle = fopen("newtest1.txt", "r");
if ($handle) {?>
<form action="checkbox-form.php" method="post">
<?php
while (($line = fgets($handle)) !== false) {
?>
<input type="checkbox" name="formDoor[]" value="<?php echo $line; ?>"/><?php echo $line; ?><br />
<?php
}
}
?>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
fclose($handle);

?>


I googled to come this far, can somebody help me?

Thanks in advance.

Answer

"formDoor" is a key in your $_POST associative array (which is similar to a dictionary here). You can access it via $_POST['formDoor'], and check for its existence via isset($_POST['formDoor']).

Outputting the formDoor parameter to the file can be done like this:

if(isset($_POST['formDoor'])) {
    $formDoor = $_POST['formDoor'];
    // check if the formDoor field is actually an array
    if(is_array($formDoor)) {
        // combine the array values into a string
        $data = implode('',$formDoor);
        file_put_contents('data.txt', $data);           
    }
Comments