I have a web form and a processor.php file that outputs the form data to a text file. The output currently puts all new info on one line per form field with a line break so for two form submissions, the output looks like this:

ITEMS SELECTED: one
two
three
INFORMATION:
First Name: John
Last Name: Smith

ITEMS SELECTED:
one
three
INFORMATION:
First Name: Bob
Last Name: Jones

I would like it to output the text into a tab-delimited format that will make it easy to import into excel so that the form field labels are appended to the top row and every form field submission gets plugged into its corresponding column.

Ideally, it would look like this:

ONE TWO THREE First Name Last Name
X X X John Smith
X X Bob Jones

Does anyone know how to re-format this to generate this type of output?

Here's my code:

// Checkbox handling
$field_1_opts = $POST['field_1'][0]."
". $
POST['field_1'][1]."
". $_POST['field_1'][2];

$fileLine = "ITEMS SELECTED: $field_1_opts
INFORMATION: " . $POST[' '] . "
First Name: " . $
POST['field_2'] . "
Last Name: " . $POST['field_3'] . "
Title: " . $
POST['field_4'] . "
Organization: " . $POST['field_5'] . "
Investor Type: " . $
POST['field_6'] . "
Address 1: " . $POST['field_7'] . "
Address 2: " . $
POST['field_8'] . "
City: " . $POST['field_9'] . "
State/Province: " . $
POST['field_10'] . "
Zip Code/Zone: " . $POST['field_11'] . "
Phone: " . $
POST['field_12'] . "
E-mail: " . $POST['field_13'] . "
Questions/Comments: " . $
POST['field_14'] . "
Country: " . $_POST['field_15'] . "
Date and Time: " . $dtstamp . "

";
$filename = 'kitrequest.txt';
if (is_writable($filename)) {

		    if (!$handle = fopen($filename, 'a'))
		    {
		         echo "Cannot open file ($filename)";
		         exit;
		    }
		    if (fwrite($handle, $fileLine) === FALSE) {
		        echo "Cannot write to file ($filename)";
		        exit;
		    }

		    fclose($handle);

		} else {
		    echo "The file  is not writable";
		}

include("confirm.html");

?>

    8 days later

    CSV files are simply in the format of each row being on a separate line, and each column being separated by a comma. For example:

    row1column1, row1column2, row1column3
    row2column1, row2column2, row2coumn3

    If your data has commas in it, it has to be in quotes:

    "row1, column1", "row1, column2", etc, etc

    So your code, when updated for this format, would be:

    
    function quote_encapse($str)
    {
      return '"'.$str.'"';
    }
    
    // Checkbox handling
    $field_1_opts = $_POST['field_1'][0]."
    ". $_POST['field_1'][1]."
    ". $_POST['field_1'][2];
    
    // Saving $_POST['field_1'] and initializing array
    $fileLine = array(0=>$field_1_opts);
    
    foreach($_POST as $name => $value) {
    
    /* This is my lazy way of changing the code,
       so I don't have to do a ton of typing
       All it does is go through the POSTed variables
       and if the name that is given has the word
       "field_" in it, it will store it to the CSV file */
    
      if($name == "field_1") {
        // Just continue to the next one
        // we already saved this one
        continue;
      }
    
      if(strpos($name, "field_") > -1)  {
        $fileLine[] = $value;
      }
    
    }
    
    // Adding your time stamp
    $fileLine[] = $dtstamp;
    
    // This will put quotes around our values
    $fileLine = array_map("quote_encapse", $fileLine);
    
    // Turning fileLine from an array into a string
    // separating each element with a comma
    $fileLine = implode(",", $fileLine);
    
    
    $filename = 'kitrequest.csv';
    
    if (is_writable($filename)) {
      if (!$handle = fopen($filename, 'a'))
      {
        echo "Could not open the order database. Please contact the admin.";
        exit;
      }
      if (fwrite($handle, $fileLine) === FALSE) {
    
    // Security issue: do not expose writable filenames
    // to the public, even if there's an error!
    echo "Could not save your order. Please contact the admin.";
      exit;
      }
    
      fclose($handle);
    
    } else {
      echo "The order database is not available right now. Please contact the admin.";
    }
    
    include("confirm.html");
    
    ?>

    I have not tested this code, so I can't be sure it works, so let me know if you have any problems. Don't test it on a live server.

    Also, this is not an ideal way to do this. You should use a database. Databases can be scary for beginners, but PHP is nearly useless without them, and they aren't all that hard. PM me if you need a link to a good tutorial for beginners, it is really worth your while.

      3 months later

      mate, it's 1am i'm tired i looked everywhere for this i just wanted it to post the data in the columns. you are my HERO! IT WORKS! why for 2 hours have i found nothing! i like php but COME ON! again hero. Thank You.

        two minor problems so far 1 - the data gets posted into the .csv file in columns but continues on the same row as more entries get posted. how do i tell it to find the last entry and post below it on the next row?

        2 the date/time stamp doesn't post. (not THAT important right now)

          You need to add a newline ("\n") at the end of each line's output.

          Also, if using PHP5, there is a built-in [man]fputcsv/man function you could use for this. Besides not having to do the implode, it takes care of things like quoting fields with commas in them and escaping quotes in the data.

            could you post an example of that as i understand what your saying but i'm a few steps away from generating my own code from scratch.

              Twitch: if you follow the link to the manual you'll find an example below it

                it's not pretty but it outputs to the csv in columns

                <?php
                //start of new code
                function quote_encapse($str)
                {
                return '"'.$str.'"';
                }

                // Checkbox handling
                $field__opts = $POST['field'][1]."
                ". $POST['field'][2];

                // Saving $POST['field'] and initializing array
                $fileLine = array(0=>$field__opts);

                foreach($_POST as $name => $value) {

                if($name == "field") {
                // Just continue to the next one
                // we already saved this one
                continue;
                }
                if(strpos($name, "field
                ") > -1) {
                $fileLine[] = $value;

                }

                }

                // Adding your time stamp
                $fileLine[] = $dtstamp;

                // This will put quotes around our values
                //$fileLine = array_map("quote_encapse", $fileLine);

                // Turning fileLine from an array into a string
                // separating each element with a comma
                $fileLine = implode(",", $fileLine);
                // end of new code

                -- and here is the output csv file

                First Name	Last Name	Address 1	Address 2	City	Province	Postal Code	Phone Number	Email Address
                
                
                Curtis	Church	Davis St	Here	Jar	On	a1b2c3	519-123-1234	[email]admi@twitchto.com[/email]
                Ron	Laba	Another St	Po Box	Jack	On	a1b2c	519519519	[email]agai@twitchto.com[/email]

                -- bad -- It for some reason makes a space for 2 rows and skips the first column
                -- good -- it keeps the text in columns and the new rows below each other for each new entry

                -- bad -- dtstamp is useless outputs nothing (i tried a hidden field on the form without luck)

                -- bad -- viewing the .csv file in notepad shows a square box (special character) separating each entry in one long run on line. previously it would load without the special character and each entry was a line of it's own.

                Any help with this is greatly appreciated i'm guessing at this point i'm a beginner at php.

                  Write a Reply...