Parse csv file with column name as key

Whenever we are dealing with CSV, we fill that we can get value of CSV row as array. Therefore, I come with this small solution for parse CSV like array structure

We taken column name as key and find value of that row using key index.
Here is the code example.

To get column name as key, we create a class. using this class, you can get array of array of CSV that with column name as an array key.


class csvParse
  var $mappings = array();

  function parseFile($filename)
//open the file
    $id = fopen($filename, "r"); 
/*This will get us the main column names */
    $data = fgetcsv($id, filesize($filename)); 

       $this->mappings = $data;

    while($data = fgetcsv($id, filesize($filename)))
            foreach($data as $key => $value)
               $converted_data[$this->mappings[$key]] = addslashes($value);
	/* put each line into  its own entry in  the $table array   */
            $table[] = $converted_data; 
   //close file
    return $table;




Speak Your Mind

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: