Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Parsing CSV file using php SplFileObject class.

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 1.24k
    Comment on it

    The SplFileObject class provides an object oriented interface for a file.

    $file="upload_file.csv"; //file to parse
    

    Steps:

    1) Create SplFileObject class object to the csv file.

    $srcFile = new SplFileObject($file);
    

    2)Now loop till end of file found.

    while (!$srcFile->eof()) //eof() returns true if file is at EOF else false. 
        {
            $data=$file->fgetcsv(); // gets a line from the csv file and returns an fields array. 
    
        }
    

    Similarly for writing csv :

    $arr = array (
        array('1', '2', '3', '4'),
        array('5', '6', '7')
       );
    
    $file = new SplFileObject('file.csv', 'w');
    
    foreach ($arr as $fields) {
        $file->fputcsv($fields); //this method works only in php 5.4 and above
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: