Theodore Steiner Theodore Steiner - 1 month ago 16
PHP Question

Print Variable Name with CVS Input

I am passing field inputs to a .csv sheet, but I was wondering if it was possible to have the variable name print along with the value?

Here is how I'm printing to the .cvs:

PHP

<?php
$csvdata = $firstName . ", " . $lastName . ", " . $homeAddress . ", " . $homeAddressTwo . ", " . $city . ", " . $province . ", " . $postalCode . ", " . $homePhone . ", " . $personalEmail . ", " . $confirmEmail . ", " . $oectaNumber . ", " . $memberStatus . ", " . $teacherTraining . ", " . $teachingYears . "," . $employmentHistoryValues;
$fp = fopen("formdata.csv", "a");
if($fp)
{
fwrite($fp, $csvdata . "\n");
fclose($fp);
}
?>


In the CSV document itself, the results are fairly easy to decipher but the form I am drawing from has a bunch of dynamic inputs that will generate multidimensional arrays and some of the inputs are textareas, so I wanted to test out this theory.

Answer

You can for example create a header csv row with the column names. You can achieve this by:

  $csv = 'col1, col2.....'.PHP_EOL;
  foreach ($data as $item) {
      $csv .= $item['val1'].','.$item['val2'].....PHP_EOL;
  }
  // write $csv to file

This will be helpful if you open the csv file in excel or open office.

But if you want to key name + value:

  foreach ($data as $key => $item) {
      $csv .= $key.'=>'.$item['val1'].',';
  }

This is example for one dimensionsl array. If you have multi dimensional you will have nested loop instead.

Comments