Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created September 11, 2017 13:18
Show Gist options
  • Save kuntalchandra/4f64fbf5f95d41d5d15eac72da366934 to your computer and use it in GitHub Desktop.
Save kuntalchandra/4f64fbf5f95d41d5d15eac72da366934 to your computer and use it in GitHub Desktop.
MySQL to CSV Converter
<?php
$exportData = [
'db0' => ['table0', 'table1'],
'db1' => ['table0']
];
$user = 'test';
$password = 'test123';
$host = '127.0.0.1';
$path = '/tmp';
foreach ($exportData as $db => $tables) {
foreach ($tables as $table) {
$csvFile = $path . '/' . $db . '.' . $table . '.csv';
$command = 'mysql -u ' . $user . ' -h' . $host . ' -p' . $password . ' -B -e "select * from ' . $db . '.' . $table . ' limit 10;"';
//NOTE: change the separator as required; ',' is not suitable always
$command .= '| sed "s/\'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > ' . $csvFile; //this regex is taken from stackoverflow; can't take its credit
shell_exec($command);
if (file_exists($csvFile)) { //remove column header
$command = "sed -i 1d $csvFile";
shell_exec($command);
}
echo "Created $csvFile\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment