将html表单值转换为csv时没有获取标题

I am trying to get values in csv file from html form. Following is the code I am using

my.php:

if($error == '')
{
    $file_open = fopen("contact_data.csv", "a");
    $no_rows = count(file("contact_data.csv"));
    if($no_rows > 1)
    {
        $no_rows = ($no_rows - 1) + 1;
    }
    $form_data = array(
        'sr_no'     =>  $no_rows,
        'name'      =>  $name,
        'email'     =>  $email,
        'subject'   =>  $subject,
        'message'   =>  $message
    );
    fputcsv($file_open, $form_data);
    $error = '<label class="text-success">Thank you for contacting us</label>';
    $name = '';
    $email = '';
    $subject = '';
    $message = '';
}

but I am getting csv with no headers. (in csv format)

   test,test@g.com,test_sub,test_msg
   user,user@g.com,user_sub,user_msg

Expected Output: (in csv format)

    name, email,      subject,  message
    test, test@g.com, test_sub, test_msg
    user, user@g.com, user_sub, user_msg

When you pass the associative array $form_data to the fputcsv function the way you do - fputcsv($file_open, $form_data), it outputs only the values part of the associative array and not the keys.

So you will have to explicity add the keys write the keys part .i.e., the headers to the csv. You can do it in one of the following ways -


Fetch the keys dynamically and store it a separate array:

$keys = [];    // declare new array to store key values

foreach($form_data as $key => $value) {
    array_push($keys, $key);
}

Or harcode the keys into an array:

$keys = array('name','email','subject','message');

Now you can write to the csv file in the following way -

fputcsv($file_open, $keys);

And then write your second fputcsv() - fputcsv($file_open, $form_data);

It won't cause any problems because you have opened the csv file in "a" (append) mode.