Showing posts with label CSV. Show all posts
Showing posts with label CSV. Show all posts

Sunday, 27 July 2014

Convert CSV to Two dimensional array (2D Array) - PHP 2

When you get the data from CSV file, It will return return array of each row. To work with this, we need to convert it as 2D array. So, this following code snippet will help you to covert CSV array to 2D array. In this we used PHP's array_combine function.

FUNCTION DEFENITION
function get2DArrayFromCsv($file, $delimiter) {
    if (($handle = fopen($file, "r+")) !== FALSE) {
        $i = 0;
        $data2DArray = array();
        while (($lineArray = fgetcsv($handle, 0, $delimiter)) !== FALSE) {
            for ($j = 0; $j < count($lineArray); $j++) {
                $data2DArray[$i][$j] = $lineArray[$j];
            }
            $i++;
        }
        fclose($handle);
    }
    return $data2DArray;
}

HOW IT WORKS

* Just used incremental variable $i to mention number of row in 2D array.
* Once finished the iteration for a row, then increment $i for the next row.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
get2DArrayFromCsv($file_path, ',');
Recommended Article : Convert CSV to JSON with header row as key - PHP

Have any doubt? Feel free to comment here!!!


Wednesday, 16 July 2014

Convert CSV to JSON with header row as key - PHP 1

When you get the data from CSV file, It will return return array of each row. If we want this array in JSON as header row as key and cell value as value, We can use PHP's array_combine function.

So, We can use this following function to achieve this task.

FUNCTION DEFENITION
function getJsonFromCsv($file,$delimiter) { 
    if (($handle = fopen($file, 'r')) === false) {
        die('Error opening file');
    }

    $headers = fgetcsv($handle, 4000, $delimiter);
    $csv2json = array();

    while ($row = fgetcsv($handle, 4000, $delimiter)) {
      $csv2json[] = array_combine($headers, $row);
    }

    fclose($handle);
    return json_encode($csv2json); 
}
HOW IT WORKS

* Just read the first line separately and merge it into every row.
* The above function opens a file handle, reads the first line into $headers
* Then reads the remaining lines.
* It combines each line with the $headers.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
getJsonFromCsv($file_path, ',');
Recommended Article : Convert CSV to Two dimensional array (2D Array) - PHP

Have any doubt? Feel free to comment here!!!