Forum Moderators: coopster

Message Too Old, No Replies

Saving and Reading CSV

What am I doing wrong?

         

thing3b

4:03 am on Mar 5, 2008 (gmt 0)

10+ Year Member



I am having a problem with the following code. This is my test class to get my understanding of the fputcsv and fgetcsv functions correct.

All I intend to do it post CSV data with fputcsv, read it with fgetcsv and ensure that the data is still correct.

If everything works the message 'Yay I can save to a CSV' should show.

My PHP Version is 5.2.5 (Not sure if this makes a difference).


<?
// Set up our paths
$filePath = 'test.csv';
$originalUserData = array(
'\\\\',
'\\',
'"',
'",',
'{',
'}',
'","',
"','",
":(",
);

// Test writting the CSV
$file = fopen($filePath, 'a');
fputcsv($file,$originalUserData);
fclose($file);

// Test reading the CSV
$userDataFromCSV = array();
$fileHandle = fopen($filePath, "r");
while (($data = fgetcsv($fileHandle)) !== FALSE && $data != null) {
$userDataFromCSV = $data;
}

// Check that everything has worked and we can save to CSV fine
if (count($originalUserData)!=count($userDataFromCSV)){
echo 'Something is wrong';
} else {
$diff = array_diff_assoc($originalUserData, $userDataFromCSV);
if (count($diff)>0){
echo 'Something is wrong';
} else {
echo 'Yay I can save to a CSV';
}
}

// Data for debugging
var_dump($originalUserData);
var_dump($userDataFromCSV);

jatar_k

2:05 pm on Mar 5, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



is nothing working?

I would suggest breaking the steps. Leave your writing code and get that working first. To test what was written, or if anything was, then just download the file in ftp and check.

You need to isolate what exectly isn't working.

thing3b

7:37 pm on Mar 5, 2008 (gmt 0)

10+ Year Member



What seems to be happening is that the fputcsv function is not escaping data like it should.