Last Updated: February 25, 2016
·
1.872K
· mbunge

Tools: Import and export of CSV and JSON files

Occasion

For some reasons we need to handle imports or exports of data. Approved and well-known file formats are json, csv or xml. In my case In my case I often need to translate CSV from Excel to json data.

Therefore I wrote a simple profile-based php class which is able to handle CSV and JSON files called ImpEx.

Details about ImpEx

ImpEx is managing profiles as anonymous functions. Each profile receive current ImpEx object and data of previous profile and return processed data. All profiles will executed by running order.

Some action

<?php 
//attach profiles
$impEx->addProfile('json.import', function($impEx,$data){
    $data = $impEx->importFromJson(dirname(__FILE__) . '/data/import_address.json');
    $newData = array();
    foreach ($data as $key => $value) {
        $street = $addressArray[0];
        $postalcode = $addressArray[2];
        $city = $addressArray[1];

        $newData[] = array(
            'postalcode' => mb_convert_encoding($postalcode, 'ISO-8859-1'),
            'city' => mb_convert_encoding($city, 'ISO-8859-1'),
            'street' => mb_convert_encoding($street, 'ISO-8859-1'),
        );
    }

  //
    return $newData;

});

$impEx->addProfile('csv.export', function($impEx,$data){
    $filename = dirname(__FILE__) . '/data/export_address.csv';
    $impEx->exportToCSV($filename,$data,ImpEx::CSV_DELIMITER_EXCEL, ImpEx::CSV_ENCLOSURE, true);
});

//executeprofiles
$impEx
    ->executeProfile('olddata.json.import')
    ->executeProfile('olddata.csv.export');
?>

Get the code

Visit ImpEx gist with example