Location: PHPKode > scripts > XLS Export > xlsexport.php
<?php

// (c) z3n - hide@address.com - www.overflow.biz - hide@address.com

/*
	This class requires PEAR Spreadsheet Excel Writer Package
	http://pear.php.net/package/Spreadsheet_Excel_Writer/
*/

require_once('Spreadsheet/Excel/Writer.php');

class XLSExport {
	private $db;
	private $server;
	private $port;
	private $user;
	private $password;
	private $tables;
	private $link;
	private $xls;
	private $fn;
	
	public $is_error;
	

	public function __construct($server, $user, $password, $db, $tables, $memory_limit="1G", $save_dir="") {
		set_time_limit(0);
		ini_set("memory_limit",$memory_limit);
		
		$this->db = $db;
		$this->user = $user;
		$this->password = $password;
		$this->is_error=0;
		
		$sa = explode(":", $server);
		$this->server = $sa[0];
		$this->port = isset($sa[1]) ? $sa[1] : 3306;
		unset($sa);
		
		$this->tables = !is_array($tables) ? array($tables) : $tables;
		$this->is_error=0;
		
		$this->link = mysql_connect($this->server, $this->user, $this->password) or $this->error(mysql_error());
		mysql_select_db($this->db, $this->link) or $this->error(mysql_error());
		
		$this->fn = $save_dir == "" ? dirname(__FILE__) : $save_dir;
		$this->fn .= "xls_export_".md5(time().mt_rand()).".xls";

		$this->xls=new Spreadsheet_Excel_Writer($this->fn);

		if (defined("lib_cache"))
			$this->xls->setTempDir(lib_cache);
	}
	
	public function export() {
		foreach ($this->tables as $table) {
			// query
			$res = mysql_query("select * from ".$table, $this->link) or $this->error(mysql_error());
			$colnames = array();
			
			// add new sheet
			$sheet = $this->xls->addWorksheet($table);
			
			for ($i = 0;$i < mysql_num_fields($res);$i++) {
				$fld = mysql_fetch_field($res, $i);
				$colnames[] = '"'.$fld->name.'"';

				// add cols to sheet
				$sheet->write(0,$i,$fld->name);
			}
			
			if (mysql_num_rows($res) > 0)
				for ($j = 1;$row = mysql_fetch_array($res, MYSQL_NUM);$j++)
					for ($i = 0;$i < sizeof($row);$i++)
						$sheet->write($j,$i,utf8_decode($row[$i]));
		}

		$this->xls->close();
		return $this->fn;
	}
	
	public function __destruct() {
		@ mysql_close($this->link);
	}

}

?>
Return current item: XLS Export