webservice/scripts/jobs/sql2csv.php
2015-09-18 09:53:21 +00:00

76 lines
2.1 KiB
PHP

<?php
// --- Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(__DIR__ . '/../../application'));
// --- Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// --- Composer autoload
require_once realpath(__DIR__ . '/../../vendor/autoload.php');
// --- Create application, bootstrap, and run
$application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
try {
$opts = new Zend_Console_Getopt(
//Options
array(
'help|?' => "Displays usage information.",
'sqlfile=s' => "",
'csvfile=s' => "",
)
);
$opts->parse();
} catch (Zend_Console_Getopt_Exception $e) {
echo $e->getUsageMessage();
exit;
}
//Usage
if(isset($opts->help))
{
echo "\n";
echo $opts->getUsageMessage();
echo "Génération d'un fichier CSV à partir d'un fichier SQL.";
echo "\n";
exit;
}
$c = new Zend_Config($application->getOptions());
try {
//$dbMaster = Zend_Db::factory($c->resources->db);
$dbSlave = Zend_Db::factory(new Zend_Config(array(
'adapter' => 'mysqli',
'params' => array(
'host' => '195.154.170.169:3306',
'username' => 'wsuser',
'password' => 'wspass2012',
'dbname' => 'sdv1',
'driver_options' => array(
MYSQLI_INIT_COMMAND => "SET NAMES utf8",
),
)
)));
} catch (Zend_Db_Exception $e) {
$e->getMessage();
}
$sql = file_get_contents($opts->sqlfile);
$rows = $dbSlave->fetchAll($sql);
if (count($rows) > 0) {
$fp = fopen($opts->csvfile.'.tmp', 'w');
//Write header
$headers = array_keys($rows[0]);
fputcsv($fp, $headers, ',', '"');
//Write content
foreach($rows as $fields) {
fputcsv($fp, $fields, ',', '"');
}
fclose($fp);
rename($opts->csvfile.'.tmp', $opts->csvfile);
} else {
file_put_contents($opts->csvfile, '');
}