
 Ramesh Narayan Jangid - 2023-02-09 11:00:12
//Example:
define('HOSTNAME', '127.0.0.1');
define('USERNAME', 'root');
define('PASSWORD', 'shames11');
define('DATABASE', 'sdk2');
$mySqlCsv = new downloadCSV();
$mySqlCsv->sql = 'SELECT * FROM `lnk_app_customer`';
$mySqlCsv->csvFilename = 'ramesh.csv';
$mySqlCsv->initDownload();
class downloadCSV
{
	/**
	 * @var string SQL whose output is used to generate a CSV file.
	 */
	public $sql;
	/**
	 *  @var string Name to be used to save CSV file on client machine.
	 */
	public $csvFilename;
	/**
	 * Initialise download.
	 *
	 * @return void
	 */
	public function initDownload()
	{
		$tmpFilename = $this->executeSql();
		$this->flushTempFile($tmpFilename);
	}
	/**
	 * Executes SQL and saves output to a temporary file on server end.
	 *
	 * @return string Tempory filename where SQL output is saved.
	 */
	private function executeSql()
	{
		// Generate temporary file for storing output of shell command on server side.
		$tmpFilename = tempnam(sys_get_temp_dir(), 'CSV');
		// Shell command.
		$shellCommand = 'mysql \\
			--host='.escapeshellarg(HOSTNAME).' \\
			--user='.escapeshellarg(USERNAME).' \\
			--password='.escapeshellarg(PASSWORD).' \\
			--database='.escapeshellarg(DATABASE).' \\
			--execute='.escapeshellarg($this->sql).' \\
			| sed -e \'s/"/""/g ; s/\t/","/g ; s/^/"/g ; s/$/"/g\' > '.escapeshellarg($tmpFilename);
		// Execute shell command
		shell_exec($shellCommand);
		return $tmpFilename;
	}
	/**
	 * Flushes sql output in temp file to client end.
	 *
	 * @return void
	 */
	private function flushTempFile($tmpFilename)
	{
		// Set CSV headers
		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename={$this->csvFilename}");
		header("Pragma: no-cache");
		header("Expires: 0");
		// Stream temp file content to browser.
		$src = fopen($tmpFilename, 'r');
		$dest = fopen('php://output', 'w');
		stream_copy_to_stream($src, $dest);
		fclose($src);
		fclose($dest);
	}
}