PHP to CSV format

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

PHP to CSV format

Post by BAZAZU »

Hi im desperately in need of some help here..
Im exporting my html page data to csv but i am unable to get the data onto a new column the code is as follows

HTML FORM

Code: Select all

 <form id="form1" name="form1" method="post" action="index.php">
    <table class="formatTblClass">
    <tr>
    <th colspan="6"><?=$message;?></th>
    </tr>
    <tr>
    <td width="68"><span>First Name</span></td>
    <td width="215"><input class="Name" type="text" name="fn" id="fn" /></td>
    <td width="62"><span>Last Name</span></td>
    <td colspan="3"><input class="Name" name="ln" type="text" id="ln" size="50" /></td>
    </tr>
    <tr>
    <td colspan="6"><table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="71">Address</td>
    <td width="721"><input class="Address" name="address" type="text" id="address" size="100" /></td>
    </tr>
    </table></td>
    </tr>
    <tr>
    <td><span>City</span></td>
    <td><input class="City" type="text" name="city" id="city" /></td>
    <td><span>State</span></td>
    <td width="148"><input class="State" type="text" name="state" id="state" /></td>
    <td width="24"><span>ZIP</span></td>
    <td width="255"><input class="ZIP" type="text" name="zip" id="zip" /></td>
    </tr>
    <tr>
    <td><span>Phone</span></td>
    <td><input class="Phone" type="text" name="phone" id="phone" /></td>
    <td><span>Email</span></td>
    <td><input class="Email" type="text" name="email" id="email" /></td>
    <td><input name="emailMe" type="checkbox" id="emailMe" value="Yes" checked="checked" /></td>
    <td>Please send me email</td>
    </tr>
    <tr>
    <td colspan="6"><span>Comments
    <textarea name="comments" id="comments" cols="45" rows="5"></textarea>
    </span>
    <div align="center">
    <input type="submit" name="Submit" id="Submit" value="Submit" />
    <input type="reset" name="Reset" id="button" value="Reset" />
    </div></td>
    </tr>
    </table>
    </form>


PHP FILE

Code: Select all

   <?php
     
    // Receiving variables
    @$pfw_ip= $_SERVER['REMOTE_ADDR'];
    @$fn = addslashes($_POST['fn']);
    @$ln = addslashes($_POST['ln']);
    @$address = addslashes($_POST['address']);
    @$city = addslashes($_POST['city']);
    @$state = addslashes($_POST['state']);
    @$zip = addslashes($_POST['zip']);
    @$phone = addslashes($_POST['phone']);
    @$email = addslashes($_POST['email']);
    @$emailMe = addslashes($_POST['emailMe']);
    @$comments = addslashes($_POST['comments']);
     
    // Validation
    //saving record in a text file
    $pfw_file_name = "formtest.csv";
    $pfw_first_raw = "fn,\rln,\raddress,\rcity,\rstate,\rzip,\rphone,\remail,\remailMe,\rcomments\r\n";
    $pfw_values = "$fn,\r$ln,\r$address,\r$city,\r$state,\r$zip,\r$phone,\r$email,\r$emailMe,\r".str_replace ("\r\n","<BR>",$comments )."\r\n";
    $pfw_is_first_row = false;
    if(!file_exists($pfw_file_name))
    {
    $pfw_is_first_row = true ;
    }
    if (!$pfw_handle = fopen($pfw_file_name, 'a+')) {
    die("Cannot open file ($pfw_file_name)");
    exit;
    }
    if ($pfw_is_first_row)
    {
    if (fwrite($pfw_handle, $pfw_first_raw ) === FALSE) {
    die("Cannot write to file ($pfw_filename)");
    exit;
    }
    }
    if (fwrite($pfw_handle, $pfw_values) === FALSE) {
    die("Cannot write to file ($pfw_filename)");
    exit;
    }
    fclose($pfw_handle);
     
    echo("<p align='center'><font face='Arial' size='3' color='#FF0000'>thanx</font></p>");
    ?>


THIS IS THE OUTPUT I GET

fn
ln
address
city
state
zip
phone
email
emailMe
comments
Tom
Sawyer
shady lane
new york
new york
NY124
123456789
tom@sawyer.com
Yes
comments



THIS IS THE OUTPUT I AM LOOKING FOR
fn Tom Harry
ln Sawyer Potter
address shady lane magic lane
city new york xyz
state new york xyz
zip NY124 12343
phone 123456789 987654321
email tom@sawyer.com harry@magic.co.uk
emailMe Yes Yes
comments comments this is the comment


Plz help me on this one
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

fwrite adds lines to files, not columns, so my first suggestion is to put the labels along the first row, then one user per row beneath it.

Code: Select all

foreach ($_POST as $key => $value)
{
    $_POST[$key] = addslashes($value);
}

$string = '';
foreach ($_POST as $key => $value)
{
    $string .= $value . ",";
}

$string = rtrim($string, ",");
$string .= "\r\n";

$fh = fopen($file, 'a+');
fwrite($fh, $string);
fclose();
Last edited by Celauran on Sun Nov 14, 2010 12:05 pm, edited 1 time in total.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

If you absolutely must add columns rather than rows, you'll need to read what's currently in the file, combine with your new data line by line, then write back to the file. Something like this:

Code: Select all

foreach ($_POST as $key => $value)
{
    $_POST[$key] = addslashes($value);
}

$fh = fopen($file, 'r');
while (!feof($fh))
{
    $existing_data[] = fgets($fh, 1024);
}
fclose($fh);

$string = '';
for ($i = 0; $i < count($existing_data); $i++)
{
    $string .= $existing_data[$i] . "," . $_POST[$i] . "\r\n";
}

$fh = fopen($file, 'w');
fwrite($fh, $string);
fclose();
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

Re: PHP to CSV format

Post by BAZAZU »

Thanks mate, being a newbie am unable to integrate it into the script could you please guide me with first name and last name in the form ill get some hint from that and integrate in into the rest of my script. And the reason i want to enter the data top to bottom column wise is that the actual form am working on consists of 240+ questions and on importing it into csv half of the data does not show due to unavailability of columns.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

I've reworked your script some, commenting as appropriate

Code: Select all

    // Receiving variables
    // @$pfw_ip= $_SERVER['REMOTE_ADDR'];
    // @$fn = addslashes($_POST['fn']);
    // @$ln = addslashes($_POST['ln']);
    // @$address = addslashes($_POST['address']);
    // @$city = addslashes($_POST['city']);
    // @$state = addslashes($_POST['state']);
    // @$zip = addslashes($_POST['zip']);
    // @$phone = addslashes($_POST['phone']);
    // @$email = addslashes($_POST['email']);
    // @$emailMe = addslashes($_POST['emailMe']);
    // @$comments = addslashes($_POST['comments']);
    
    // I've replaced this with a single loop.  Rather than manually specify 
    // $_POST['fn'], $_POST['ln'], etc, I'm just running through everything 
    // contained in $_POST.  The block above and the block below basically 
    // do the same thing.
    foreach ($_POST as $key => $value)
    {
        $_POST[$key] = addslashes($value);
    }
    
     
    // saving record in a text file
    $pfw_file_name = "formtest.csv";
    
    // Let's store this as an array so we can loop through it
    $pfw_first_row = array("fn", "ln", "address", "city", "state", "zip", "phone", "email", "emailMe", "comments");

    // This is what's causing your values to be saved below the labels rather 
    // than beisde them. We've already got them in the $_POST array, so we'll 
    // use that.
    // $pfw_values = "$fn,\r$ln,\r$address,\r$city,\r$state,\r$zip,\r$phone,\r$email,\r$emailMe,\r".str_replace ("\r\n","<BR>",$comments )."\r\n";

    $pfw_is_first_row = false;

    if(!file_exists($pfw_file_name))
    {
        $pfw_is_first_row = true;
        // If the file doesn't exist, let's create it
        shell_exec('touch ' . $pfw_file_name);
        
    }
    else
    {
        if (!$pfw_handle = fopen($pfw_file_name, 'r'))
        {
            die("Cannot open file ($pfw_file_name)");
            exit;
        }
        // If the file exists, we want to read in its contents
        else
        {
            // Until we reach the end of the file
            while (!feof($pfw_handle))
            {
                // We'll read in one line at a time and store it in an array
                $existing_file[] = fgets($pfw_handle, 1024)
            }
        }
        // We only opened it for reading
        fclose($pfw_handle)
    }
    
    // Now we're going to open the file for writing
    if (!$pfw_handle = fopen($pfw_file_name, 'w+')
    {
        die("Cannot open file {$pfw_file_name} for writing");
    }
    else
    {
        // We need to write in the labels
        if ($pfw_is_first_row == true)
        {
            // Write the file one line at a time
            for ($i = 0; $i < count($pfw_first_row); $i++)
            {
                // We need to combine the first label and the first row of data
                $string = $pfw_first_row[$i] . "\t" . $_POST[$i] . "\r\n";
                fwrite($pfw_handle, $string);
            }
        }
        else
        {
            // Same as above, except $existing_file contains labels plus whatever
            // was already in the file
            for ($i = 0; $i < count($existing_file); $i++)
            {
                $string = $existing_file[$i] . "\t" . $_POST[$i] . "\r\n";
                fwrite($pfw_handle, $string);
            }
        }
        fclose($pfw_handle);
    }
     
    echo("<p align='center'><font face='Arial' size='3' color='#FF0000'>thanx</font></p>");
CAVEAT: I haven't actually tested this.
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

Re: PHP to CSV format

Post by BAZAZU »

Hey thanks a ton man.. love your patience..

tested it it says Parse error: syntax error, unexpected '}' in C:\xampplite\htdocs\eg\index.php on line 60

Code: Select all

    else
    {
        if (!$pfw_handle = fopen($pfw_file_name, 'r'))
        {
            die("Cannot open file ($pfw_file_name)");
            exit;
        }
        // If the file exists, we want to read in its contents
        else
        {
            // Until we reach the end of the file
            while (!feof($pfw_handle))
            {
                // We'll read in one line at a time and store it in an array
                $existing_file[] = fgets($pfw_handle, 1024)
            } [b]this is line 60.. I dont see any error here though[/b]
        }
        // We only opened it for reading
        fclose($pfw_handle)
    }
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

BAZAZU wrote:Hey thanks a ton man.. love your patience..

tested it it says Parse error: syntax error, unexpected '}' in C:\xampplite\htdocs\eg\index.php on line 60

Code: Select all

                // We'll read in one line at a time and store it in an array
                $existing_file[] = fgets($pfw_handle, 1024)
            } this is line 60.. I dont see any error here though
    }
$existing_file[] line is missing a semicolon at the end.
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

Re: PHP to CSV format

Post by BAZAZU »

thanx and sorry for being a pain.. the file ran but gave us an unexpected output

"fn "
"ln "
"address "
"city "
"state "
"zip "
"phone "
"email "
"emailMe "
"comments "

The data that was entered through the form is not captured :(
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

That's what I get for not being thorough and actually testing stuff.

Code: Select all

if ($_POST)
{
    // Receiving variables
    // @$pfw_ip= $_SERVER['REMOTE_ADDR'];
    // @$fn = addslashes($_POST['fn']);
    // @$ln = addslashes($_POST['ln']);
    // @$address = addslashes($_POST['address']);
    // @$city = addslashes($_POST['city']);
    // @$state = addslashes($_POST['state']);
    // @$zip = addslashes($_POST['zip']);
    // @$phone = addslashes($_POST['phone']);
    // @$email = addslashes($_POST['email']);
    // @$emailMe = addslashes($_POST['emailMe']);
    // @$comments = addslashes($_POST['comments']);
   
    // I've replaced this with a single loop.  Rather than manually specify
    // $_POST['fn'], $_POST['ln'], etc, I'm just running through everything
    // contained in $_POST.  The block above and the block below basically
    // do the same thing.
    foreach ($_POST as $key => $value)
    {
        $_POST[$key] = addslashes($value);
    }
     
    // saving record in a text file
    $pfw_file_name = "formtest.csv";
   
    // Let's store this as an array so we can loop through it
    $pfw_first_row = array("fn", "ln", "address", "city", "state", "zip", "phone", "email", "emailMe", "comments");

    // This is what's causing your values to be saved below the labels rather
    // than beisde them. We've already got them in the $_POST array, so we'll
    // use that.
    // $pfw_values = "$fn,\r$ln,\r$address,\r$city,\r$state,\r$zip,\r$phone,\r$email,\r$emailMe,\r".str_replace ("\r\n","<BR>",$comments )."\r\n";

    $pfw_is_first_row = false;

    if(!file_exists($pfw_file_name))
    {
        $pfw_is_first_row = true;
        // If the file doesn't exist, let's create it
        if (!$fh = fopen($pfw_file_name, "w+"))
        {
            die("Cannot create file {$pfw_file_name}");
        }
        else
        {
            fclose($fh);
        }
    }
    else
    {
        if (!$pfw_handle = fopen($pfw_file_name, 'r'))
        {
            die("Cannot open file ($pfw_file_name)");
        }
        // If the file exists, we want to read in its contents
        else
        {
            // Until we reach the end of the file
            while (!feof($pfw_handle))
            {
                // We'll read in one line at a time and store it in an array
                $existing_file[] = fgets($pfw_handle, 1024);
            }
            if (count($existing_file) == 1)
            {
                $pfw_is_first_row = true;
            }
        }
        // We only opened it for reading
        fclose($pfw_handle);
    }
   
    // Now we're going to open the file for writing
    if (!$pfw_handle = fopen($pfw_file_name, 'w+'))
    {
        die("Cannot open file {$pfw_file_name} for writing");
    }
    else
    {
        // We need to write in the labels
        if ($pfw_is_first_row == true)
        {
            // Write the file one line at a time
            for ($i = 0; $i < count($pfw_first_row); $i++)
            {
                // We need to combine the first label and the first row of data
                $string = $pfw_first_row[$i] . "\t" . $_POST[$pfw_first_row[$i]] . "\r\n";
                fwrite($pfw_handle, $string);
            }
        }
        else
        {
            // Same as above, except $existing_file contains labels plus whatever
            // was already in the file
            for ($i = 0; $i < count($existing_file); $i++)
            {
                $string = rtrim($existing_file[$i], "\r\n") . "\t" . $_POST[$pfw_first_row[$i]] . "\r\n";
                fwrite($pfw_handle, $string);
            }
        }
        fclose($pfw_handle);
    }
     
}
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

Re: PHP to CSV format

Post by BAZAZU »

Youre too good and quick at this man!!
Just one last thing.. theyre all showing up in the same block!
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

BAZAZU wrote:theyre all showing up in the same block!
Not sure I understand.
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

Re: PHP to CSV format

Post by BAZAZU »

have attached image..
Attachments
img.JPG
img.JPG (24.93 KiB) Viewed 2130 times
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP to CSV format

Post by Celauran »

Should be a tab separated text file and it opens fine for me in OOo, so I'm not sure why you're getting those boxes. You could try replacing the \t with another separator.
BAZAZU
Forum Newbie
Posts: 8
Joined: Sun Nov 14, 2010 10:18 am

Re: PHP to CSV format

Post by BAZAZU »

Celauran wrote:Should be a tab separated text file and it opens fine for me in OOo, so I'm not sure why you're getting those boxes. You could try replacing the \t with another separator.

I Used Comma and it works perfect.. thanx a ton will update you when i complete the work i am doing.. thanks again
Post Reply