Saving and Reading CSV

Discussion in 'PHP' started by thing2b, Mar 4, 2008.

  1. #1
    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);
    
    
    Code (markup):
     
    thing2b, Mar 4, 2008 IP
  2. 00johnny

    00johnny Peon

    Messages:
    149
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    What is the exact problem you having? I don't understand what your asking...
     
    00johnny, Mar 5, 2008 IP