0

I need to add form input data from an array to a CSV file in PHP.

I tried to add the data with foreach function but the data didn't appear in the CSV file with the following code:

$values = [
    'orderperson',
    'address',
    'postnumber',
    'city',
    'phone',
    'email'
];

$fh = fopen("file.csv", "w");
foreach($values as $info) {
    fputcsv($fh, $_POST[$info]);
}

If I'm correct what I'm trying to accomplish here puts all the data in one row? How I can add the data in the file like that there's only one element of array in one row like this:

1 orderperson
2 address
3 postnumber

and not like 1 orderperson 2 address 3 postnumber

2 Answers 2

1

fputcsv() delimiter must be a single character

$fh = fopen("file.csv", "w");
$delimiter = ',';
fputcsv($fh, $values, $delimiter);

alternatively, you can try this:

$values = [
'orderperson',
'address',
'postnumber',
'city',
'phone',
'email'
];

$path = 'file.csv';
$handle = fopen($path, 'w+');
foreach($values as $value) {
    fwrite($handle, $value . ',' . PHP_EOL);
}
fclose($handle);

You can later either trim last comma or use count() and avoid adding delimiter for the last element in array.


If, on the other hand, you do not wish to have comma, but new lines as a separation (but, that is no longer CSV file!!), you can replace above fwrite() line with this:

fwrite($handle, $value . PHP_EOL);
Sign up to request clarification or add additional context in comments.

2 Comments

Don't I need $_POST there somewhere cause those values are input data?
Well, without knowing your input side, there is no way to tell that. Anyway, you can replace $values array with your $_POST input, of course! This is an answer to your question how to write your values per new line, not how to handle input.
0

Alright. You appear to be on the right path. If you intend to put every entry in the $values array on a new line in the resultant .csv file, do the following:

  1. Create a function to merge the fields set in the $data array with incoming $_POST data
$postToCsv = function (array $fields, array $super) {
  return array_map(function ($field, $val) {
    return array($field, $val);
  }, $fields, $super);
};

  1. Modify the loop to use the function in the snippet above.
foreach ($postToCsv($values, $_POST) as $field) {
  fputcsv($fh, $field);
}

Also, remember to close the file operation.

fclose($fh);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.