Home > front end >  Need to add form data to CSV file but PHP Array from input values being recognised as string
Need to add form data to CSV file but PHP Array from input values being recognised as string

Time:09-23

I am trying to convert the values from an HTML form to a PHP array and from that into a new CSV row. I haven't had much success despite searching for hours. Here is where I am right now:

$fields = empty($_POST["wrdlGuess"]) ? 'null' : $_POST["wrdlGuess"];
$fh = fopen("test.csv", "a");
$delimiter = '|';
foreach ($fields as $field) {
   fputcsv($fh, $field, $delimiter);
};

This is the html form I have:

<form action="add_to_csv.php" method="POST">
    <input type="text" name="wrdlGuess[]" value="null1">
    <input type="text" name="wrdlGuess[]" value="null2">
    <input type="text" name="wrdlGuess[]" value="null3">
    <input type="text" name="wrdlGuess[]" value="null4">
    <input type="text" name="wrdlGuess[]" value="null5">
    <input type="text" name="wrdlGuess[]" value="null6">
    <button type="submit"></button>
</form>

Currently this is returning an error saying "Warning: foreach() argument must be of type array|object, string given in... [file path]". Are all the values being concatenated into a single string, which needs splitting back up?

"add_to_csv.php" is the file that contains the form, so when it is submitted it sends the data to itself. Perhaps it's better practice to use a separate file?

I'm certain this is child's play and I'm just not on the ball enough to get my head around it. Any help will be greatly appreciated, thanks for reading!

CodePudding user response:

Build a new array from the inputs and then use that in the fputcsv()

foreach ($_POST["wrdlGuess"] as $guess) {
    $guesses[] = $guess;
}
fputcsv($fh, $guesses, $delimiter);
  • Related