I am working on exporting data from a MySQL database into an Excel spreadsheet. I have found code for doing this before and it works quite well. It does not format the spreadsheet. It was also the first PHP/MySQL site I created and the data didn't need to be pretty. The current project requires formatted data.
Yesterday, I found an article that may have allowed me to do what I need to do. Like an idiot, I didn't copy the link down. I can't find it today.
Here's my code -
<?php
require_once("includes/connection.php");
require_once("includes/functions.php");
// set $closed to 0 for development
$closed = 0;
//create a sting to allow the user to see if s/he is looking at open or closed items
if ($closed) {
$filename = FILENAME."_closed";
} else {
$filename = FILENAME."_open";
}
// $data will hold the result
$data = '<table>';
// is the row a header?
$th = FALSE;
// define the separator character
$sep = '\t';
// array for keys
$thKey = array();
// are we in the first row?
$firstRow = TRUE;
// create the query
$query = "SELECT ";
$query .= "training_requirements.Training, mechanism.mechName, location.locationName, impacted_employees.groupName, ";
$query .= "training_requirements.DateReceived, training_requirements.DateStart, training_requirements.DateDue, ";
$query .= "requester.lastName, requester.firstName, impact.impactName, training_requirements.TimeNeeded, ";
$query .= "priority.priority, training_requirements.Notes ";
$query .= "FROM ";
$query .= "training_requirements, impact, impacted_employees, location, mechanism, requester, priority ";
$query .= "WHERE impact.impactId = training_requirements.impactId ";
$query .= "AND impacted_employees.groupId = training_requirements.impEmpId ";
$query .= "AND location.locationId = training_requirements.trainLocId ";
$query .= "AND mechanism.mechId = training_requirements.mechId ";
$query .= "AND requester.requesterId = training_requirements.requesterId ";
$query .= "AND priority.id = training_requirements.Priority ";
$query .= "AND training_requirements.Closed = $closed ";
$query .= "AND training_requirements.Deleted = 0";
// run the query
$result = executeQuery($connection, $query);
// process the query
if (mysqli_num_rows($result) > 0) {
while ($resource = mysqli_fetch_assoc($result)) {
if (empty($thKey)) {
foreach($resource as $key => $value) {
$thKey[] = $key;
}
}
$data .= '<tr>';
for ($i = 0; $i < count($resource); $i++) {
if ($firstRow) {
// create the header
for ($j = 0; $j < count($resource); $j++) {
$data .= '<th>';
$data .= $thKey[$j];
$data .= '</th>';
}
$data .= '</tr><tr>';
$firstRow = FALSE;
}
$data .= '<td>';
if (isset($resource[$thKey[$i]])) {
$data .= $resource[$thKey[$i]];
} else {
$data .= ' ';
}
$data .= '</td>';
}
$data .= '</tr>';
}
$data .= '</table>';
echo $data;
}
//header('Content-type: application/excel');
//header("Content-Disposition: attachment; filename={$filename}.xls");
//header("Pragma: no-cache");
//header("Expires: 0");
?>
The code continues on to allow me to display the results in a browser. I get a proper looking table in Firefox. When I un-comment the header statements at the bottom, I get a blank Excel file. No cells, no nothing.
Using Excel 2007(12.0.6715.5000) SP3 MSO (12.0.6721.5000), PHP 5.4.24, and MySQL 5.5.40. Using plugins and libraries is not an option.
Vern
your code is just fech data from MySQL and not make any excel file .
here you are a great class for making execl file
with pure XML code without any extension
<?php
/********************************/
/* Code By Mr Korosh Raoufi */
/* WwW.k2-4u.CoM */
/********************************/
/**
* Simple excel generating from PHP5
*
* #package Utilities
* #license http://www.opensource.org/licenses/mit-license.php
* #author Oliver Schwarz <oliver.schwarz#gmail.com>
* #version 1.0
*/
/**
* Generating excel documents on-the-fly from PHP5
*
* Uses the excel XML-specification to generate a native
* XML document, readable/processable by excel.
*
* #package Utilities
* #subpackage Excel
* #author Oliver Schwarz <oliver.schwarz#vaicon.de>
* #version 1.1
*
* #todo Issue #4: Internet Explorer 7 does not work well with the given header
* #todo Add option to give out first line as header (bold text)
* #todo Add option to give out last line as footer (bold text)
* #todo Add option to write to file
*/
class Excel_XML
{
/**
* Header (of document)
* #var string
*/
private $header = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
/**
* Footer (of document)
* #var string
*/
private $footer = "</Workbook>";
/**
* Lines to output in the excel document
* #var array
*/
private $lines = array();
/**
* Used encoding
* #var string
*/
private $sEncoding;
/**
* Convert variable types
* #var boolean
*/
private $bConvertTypes;
/**
* Worksheet title
* #var string
*/
private $sWorksheetTitle;
/**
* Constructor
*
* The constructor allows the setting of some additional
* parameters so that the library may be configured to
* one's needs.
*
* On converting types:
* When set to true, the library tries to identify the type of
* the variable value and set the field specification for Excel
* accordingly. Be careful with article numbers or postcodes
* starting with a '0' (zero)!
*
* #param string $sEncoding Encoding to be used (defaults to UTF-8)
* #param boolean $bConvertTypes Convert variables to field specification
* #param string $sWorksheetTitle Title for the worksheet
*/
public function __construct($sEncoding = 'UTF-8', $bConvertTypes = false, $sWorksheetTitle = 'Table1')
{
$this->bConvertTypes = $bConvertTypes;
$this->setEncoding($sEncoding);
$this->setWorksheetTitle($sWorksheetTitle);
}
/**
* Set encoding
* #param string Encoding type to set
*/
public function setEncoding($sEncoding)
{
$this->sEncoding = $sEncoding;
}
/**
* Set worksheet title
*
* Strips out not allowed characters and trims the
* title to a maximum length of 31.
*
* #param string $title Title for worksheet
*/
public function setWorksheetTitle ($title)
{
$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);
$title = substr ($title, 0, 31);
$this->sWorksheetTitle = $title;
}
/**
* Add row
*
* Adds a single row to the document. If set to true, self::bConvertTypes
* checks the type of variable and returns the specific field settings
* for the cell.
*
* #param array $array One-dimensional array with row content
*/
private function addRow ($array)
{
$cells = "";
foreach ($array as $k => $v):
$type = 'String';
if ($this->bConvertTypes === true && is_numeric($v)):
$type = 'Number';
endif;
$v = htmlentities($v, ENT_COMPAT, $this->sEncoding);
$cells .= "<Cell><Data ss:Type=\"$type\">" . $v . "</Data></Cell>\n";
endforeach;
$this->lines[] = "<Row>\n" . $cells . "</Row>\n";
}
/**
* Add an array to the document
* #param array 2-dimensional array
*/
public function addArray ($array)
{
foreach ($array as $k => $v)
$this->addRow ($v);
}
/**
* Generate the excel file
* #param string $filename Name of excel file to generate (...xls)
*/
public function generateXML ($filename = 'excel-export')
{
// correct/validate filename
$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);
// deliver header (as recommended in php manual)
header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);
header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
// print out document to the browser
// need to use stripslashes for the damn ">"
echo stripslashes (sprintf($this->header, $this->sEncoding));
echo "\n<Worksheet ss:Name=\"" . $this->sWorksheetTitle . "\">\n<Table>\n";
foreach ($this->lines as $line)
echo $line;
echo "</Table>\n</Worksheet>\n";
echo $this->footer;
}
}
?>
usage:
$xls = new Excel_XML('UTF-8', false, 'title text');
$data = array(
1 => array ('column1 text', 'coloumn2 text'),
1 => array ('column1 text', 'coloumn2 text'),
1 => array ('column1 text', 'coloumn2 text'),
);
$xls -> addArray($data);
$xls -> generateXML('file Name'); // its print code to browser use requred header to download
Related
CodeIgniter has the language class by default. I want to export all the language file into CSV format. Is there any PHP script available to parse and export the file content?
Sample file content:
<?php
$lang['Mymenu'] = "Mymenu";
$lang['AdminUser'] = "AdminUser";
The language files can also be placed inside the folders like
application/language/english
application/language/spanish ...etc
Got a solution from the gist
https://gist.github.com/timneutkens/19e58a00ff8af4663c6502a1d89990a4
Thanks for that but the solution not applicable for recursive language directories.
Here I am posting the modified version:
<?php
/**
* PHP version 5.4
* #category Export
* #package Language
* #author Tim Neutkens <tim#weprovide.com>
* #license MIT <https://opensource.org/licenses/MIT>
* #link <weprovide.com>
*/
define('ENVIRONMENT', 'production');
/**
* Placeholder for base_url function
*
* #param string $path path part of url
*
* #return string
*/
function base_url($path = '')
{
return '/'.$path;
}
/**
* Placeholder for base_url function
*
* #param string $path path part of url
*
* #return string
*/
function site_url($path = '')
{
return '/'.$path;
}
/**
* Export csv to file location
*
* #param array $data csv data
* #param string $location location to put file
*
* #return string
*/
function export_csv($data = [], $location = '',$file_name)
{
// $file_name = 'export-lang-'.time().'.csv';
$file_name = $file_name.'.csv';
$file_path = $location.'/'.$file_name;
$file = #fopen($file_path, 'w');
fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($data as $key => $value) {
fputcsv($file, [$key, $value]);
}
fclose($file);
return $file_path;
}
/**
* Load language
*
* #param string $path path to language directory.
*
* #return array
*/
function load_language($path = '')
{
// Loop through translations
/*$files = glob($path.'/*.php');
foreach ($files as $filename) {
include_once $filename;
}*/
$di = new RecursiveDirectoryIterator($path);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if(!is_dir($filename))
include_once $filename; //echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
return $lang;
}
$lang_array = array('arabic','chinese','english','french','german','italian','japanese','korean','polish','portuguese','russian','spanish','turkish','vietnam'); // List of language folders
$i=1;
$file_arr = array();
$lang1 = $lang2 = $lang3 = $lang4 = $lang5 = $lang6 = $lang7 = $lang8 = $lang9 = $lang10 = $lang11 = $lang12 = $lang13 = $lang14 = '' ;
foreach ($lang_array as $language) {
${"lang" . $i} = load_language('application/language/'.$language);
export_csv( ${"lang" . $i} , '/xampp/htdocs/CodeIginiter/language',$language);
// Lang gets filled by the above includes
$i++;
}
Place the file in the root directory of CodeIgniter and execute. CSV files will get downloaded which can easily export to excel and used for language translators.
I have a configuration table in a database, using CI3.
Each row has a unique ID, as well as a type_name and type_desc.
So as each row has a unique ID, how can I update the entire table using one update_batch query?
I obviously don't want to run a query on each row, so I'm guessing i need to build an array with the values, but how can do this with the where clause somehow within the array?! Confused.
I basically need to do this:
UPDATE check_types
SET type_name = POSTED_TYPE_NAME, type_desc = POSTED_TYPE_DESC
WHERE check_type_id = ???? POSTED_ID?????
The only way I know of to do this is to extend the db driver.
In the core folder create file with name MY_DB_mysqli_driver.php. file name assumes that the subclass_prefix defined in config.php is MY_
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_DB_mysqli_driver extends CI_DB_mysqli_driver
{
final public function __construct($params)
{
parent::__construct($params);
}
/**
* Insert_On_Duplicate_Key_Update_Batch
*
* Compiles batch insert strings and runs the queries
*
* #param string $table Table to insert into
* #param array $set An associative array of insert values
* #param bool $escape Whether to escape values and identifiers
* #return int Number of rows inserted or FALSE on failure
*/
public function insert_on_duplicate_update_batch($table = '', $set = NULL, $escape = NULL)
{
if ($set !== NULL)
{
$this->set_insert_batch($set, '', $escape);
}
if (count($this->qb_set) === 0)
{
// No valid data array. Folds in cases where keys and values did not match up
return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
}
if ($table === '')
{
if (!isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
$table = $this->qb_from[0];
}
// Batch this baby
$affected_rows = 0;
for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100)
{
$this->query($this->_insert_on_duplicate_key_update_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, 100)));
$affected_rows += $this->affected_rows();
}
$this->_reset_write();
return $affected_rows;
}
/**
* Insert on duplicate key update batch statement
*
* Generates a platform-specific insert string from the supplied data
*
* #param string $table Table name
* #param array $keys INSERT keys
* #param array $values INSERT values
* #return string
*/
private function _insert_on_duplicate_key_update_batch($table, $keys, $values)
{
foreach ($keys as $num => $key)
{
$update_fields[] = $key . '= VALUES(' . $key . ')';
}
return "INSERT INTO " . $table . " (" . implode(', ', $keys) . ") VALUES " . implode(', ', $values) . " ON DUPLICATE KEY UPDATE " . implode(', ', $update_fields);
}
}
You would use it like this:
$sql_array = array();
foreach ($data as $row)
{
$arr = array(
'check_type_id' => $row['check_type_id'],
'type_name' => $row['type_name'],
'type_desc' => $row['type_desc']
);
$sql_array[] = $arr;
}
$this->db->insert_on_duplicate_update_batch('check_types', $sql_array);
I have been using stack overflow for a good couple of years but only now made an account because I have never become so stuck that I needed to ask a question (not because I'm smart, because my code is simple!), anyway on to my question;
I am exporting a table in .xls format via PHP with information from a few tables in my MYSQL table. all the information and styling works perfectly. The only problem is that when it opens in office 2007 i get this error message:
"the file you are trying to open, 'export.xls', is a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Are you sure you want to view this file?"
So to sum up, all information is pulled from DB successful and all the styling works - I know this to be true because when I click 'yes' on the dialog box that pops up I see everything laid-out perfectly.
Below is the Excel exporter class:
/**
* Class for generating xml with multiple spreadsheets
* #author Marin Crnković
* #version 0.9
* #update_date 21.01.2009
*/
class excel_xml {
var $xml_data;
var $nl;
var $tab;
var $cols;
var $rows;
var $worksheets;
var $counters;
var $xml;
/**
* Constructor
*/
function excel_xml(){
$this->column_width = 150;
$this->debug = false;
$this->cols = array();
$this->row_array = array();
$this->rows = array();
$this->worksheets = array();
$this->counters = array();
$this->nl = "\n";
$this->tab = "\t";
}
/**
* Set debug
*/
function debug() {
$this->debug = true;
}
/**
* Generate xml
* #returns string
*/
function generate() {
// Create header
$xml = $this->create_header().$this->nl;
// Put all worksheets
$xml .= join('', $this->worksheets).$this->nl;
// Finish with a footer
$xml .= $this->create_footer();
$this->xml = $xml;
return $this->xml;
}
/**
* Create worksheet
* Uppon creating a worksheet, delete counters
* #param string $worksheet_name: name of the worksheet
*/
function create_worksheet($worksheet_name) {
$worksheet = '<Worksheet ss:Name="'.$worksheet_name.'">';
$worksheet .= $this->create_table();
$worksheet .= '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>';
// Unset the counters and rows so you can generate another worksheet table
$this->counters = array();
$this->row_array = array();
$this->rows = '';
// Add generated worksheet to the worksheets array
$this->worksheets[] = $worksheet;
}
/**
* Create table
* #returns string
*/
function create_table() {
// Create rows with the method that automaticaly sets counters for number of columns and rows
$rows = $this->create_rows();
// Table header
$table = '<Table ss:ExpandedColumnCount="'.$this->counters['cols'].'" ss:ExpandedRowCount="'.$this->counters['rows'].'" x:FullColumns="1" x:FullRows="1">'.$this->nl;
// Columns data (width mainly)
for($i = 1; $i <= $this->counters['cols']; $i++) {
$table .= '<Column ss:Index="'.$i.'" ss:Width="'.$this->column_width.'" />'.$this->nl;
}
// Insert all rows
$table .= join('', $rows);
// End table
$table .= '</Table>'.$this->nl;
return $table;
}
/**
* Add another row into the array
* #param mixed $array: array with row cells
* #param mixed $style: default null, if set, adds style to the array
*/
function add_row($array, $style = null) {
if(!is_array($array)) {
// Asume the delimiter is , or ;
$array = str_replace(',', ';', $array);
$array = explode(';', $array);
}
if(!is_null($style)) {
$style_array = array('attach_style' => $style);
$array = array_merge($array, $style_array);
}
$this->row_array[] = $array;
}
/**
* Create rows
* #returns array
*/
function create_rows() {
$row_array = $this->row_array;
if(!is_array($row_array)) return;
$cnt = 0;
$row_cell = array();
foreach($row_array as $row_data) {
$cnt++;
// See if there are styles attached
$style = null;
if($row_data['attach_style']) {
$style = $row_data['attach_style'];
unset($row_data['attach_style']);
}
// Store the counter of rows
$this->counters['rows'] = $cnt;
$cells = '';
$cell_cnt = 0;
foreach($row_data as $key => $cell_data) {
$cell_cnt++;
$cells .= $this->nl.$this->prepare_cell($cell_data, $style);
}
// Store the number of cells in row
$row_cell[$cnt][] = $cell_cnt;
$this->rows[] = '<Row>'.$cells.$this->nl.'</Row>'.$this->nl;
}
// Find out max cells in all rows
$max_cells = max($row_cell);
$this->counters['cols'] = $max_cells[0];
return $this->rows;
}
/**
* Prepare cell
* #param string $cell_data: string for a row cell
* #returns string
*/
function prepare_cell($cell_data, $style = null) {
$str = str_replace("\t", " ", $cell_data); // replace tabs with spaces
$str = str_replace("\r\n", "\n", $str); // replace windows-like new-lines with unix-like
$str = str_replace('"', '""', $str); // escape quotes so we support multiline cells now
preg_match('#\"\"#', $str) ? $str = '"'.$str.'"' : $str; // If there are double doublequotes, encapsulate str in doublequotes
// Formating: bold
if(!is_null($style)) {
$style = ' ss:StyleID="'.$style.'"';
} elseif (preg_match('/^\*([^\*]+)\*$/', $str, $out)) {
$style = ' ss:StyleID="bold"';
$str = $out[1];
}
if (preg_match('/\|([\d]+)$/', $str, $out)) {
$merge = ' ss:MergeAcross="'.$out[1].'"';
$str = str_replace($out[0], '', $str);
}
// Get type
$type = preg_match('/^([\d]+)$/', $str) ? 'Number' : 'String';
return '<Cell'.$style.$merge.'><Data ss:Type="'.$type.'">'.$str.'</Data></Cell>';
}
/**
* Create header
* #returns string
*/
function create_header() {
if (is_array($this->styles)) {
$styles = join('', $this->styles);
}
$header = <<<EOF
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<DownloadComponents/>
<LocationOfComponents HRef="file:///\\"/>
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>12525</WindowHeight>
<WindowWidth>15195</WindowWidth>
<WindowTopX>480</WindowTopX>
<WindowTopY>120</WindowTopY>
<ActiveSheet>0</ActiveSheet>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="bold">
<Font ss:Bold="1" />
</Style>
$styles
</Styles>
EOF;
return $header;
}
/**
* Add style to the header
* #param string $style_id: id of the style the cells will reference to
* #param array $parameters: array with parameters
*/
function add_style($style_id, $parameters) {
foreach($parameters as $param => $data) {
switch($param) {
case 'size':
$font['ss:Size'] = $data;
break;
case 'font':
$font['ss:FontName'] = $data;
break;
case 'color':
case 'colour':
$font['ss:Color'] = $data;
break;
case 'bgcolor':
$interior['ss:Color'] = $data;
break;
case 'bold':
$font['ss:Bold'] = $data;
break;
case 'italic':
$font['ss:Italic'] = $data;
break;
case 'strike':
$font['ss:StrikeThrough'] = $data;
break;
}
}
if(is_array($interior)) {
foreach($interior as $param => $value) {
$interiors .= ' '.$param.'="'.$value.'"';
}
$interior = '<Interior ss:Pattern="Solid"'.$interiors.' />'.$this->nl;
}
if(is_array($font)) {
foreach($font as $param => $value) {
$fonts .= ' '.$param.'="'.$value.'"';
}
$font = '<Font'.$fonts.' />'.$this->nl;
}
$this->styles[] = '
<Style ss:ID="'.$style_id.'">
'.$interior.$font.'
</Style>';
}
/**
* Create footer
* #returns string
*/
function create_footer() {
return '</Workbook>';
}
/**
* Output as download
*/
function download($filename) {
if(!strlen($this->xml)) $this->generate();
header("Cache-Control: public, must-revalidate");
header("Pragma: no-cache");
header("Content-Length: " .strlen($this->xml) );
header("Content-Type: application/vnd.ms-excel");
if(!$this->debug){
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
} else {
header("Content-Type: text/plain");
}
print $this->xml;
exit;
}
}
And this is my implementation with sensitive information censored;
$excel = new excel_xml();
$header_style = array(
'bold' => 1,
'size' => '14',
'color' => '#FFFFFF',
'bgcolor' => '#4F81BD'
);
$excel->add_style('header', $header_style);
$header_style2 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#92d050'
);
$excel->add_style('green', $header_style2);
$header_style3 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#c00000'
);
$excel->add_style('error', $header_style3);
$header_style4 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#e46d0a'
);
$excel->add_style('orange', $header_style4);
$header_style5 = array(
'bold' => 1,
'color' => '#FFFFFF',
'bgcolor' => '#c00000'
);
$excel->add_style('red', $header_style5);
/**
* Add row and attach the style "header" to it
*/
$excel->add_row(array(
'col1',
'col2',
'col3',
'col4',
'col5'
), 'header');
/**
* Add some rows, if you encapsulate the string inside asterisks,
* they will get bold using the predefined style "bold"
* If you append "|x" where x is a number, that cell will be
* merged with the x following cells
*/
$excel->add_row(array(
$Queried_Info_From_DB1,
$Queried_Info_From_DB2,
$Queried_Info_From_DB3,
$Queried_Info_From_DB4,
$Queried_Info_From_DB5
), 'red');
if(mysql_num_rows($result) == 0){
$excel->add_row(array(
'You have no info to display!|4'
), 'error');
}
/**
* Tell the object to create the worksheet.
* The passed string is the name of the worksheet
*/
$excel->create_worksheet('Your info');
/**
* If you invoke the generate method, you will get the
* XML returned or...
*/
$xml = $excel->generate();
/**
* ... you can pass the whole thing for download with
* the passed string as the filename
*/
$excel->download('Export');
You're writing a file that's spreadsheetML format, not BIFF (.xls) format, so MS Excel will complain at this discrepancy. Try saving it with a file extension of .xml (because that's what you're actually creating)
I have a function that updates fine with a single dimensional array, but with a multidimensional array (or nested array) it will not update. the document data, the BSONfield (acts as the find key), and the collection are imputed. Any Idea what i am doing wrong?
Public Static function updateDocument($collection, $BSONfield, $document){
$dbcollection = $db->selectCollection($collection);
$sdata = $document[$BSONfield];
$secureInnerDocument = array();
$secureDocument = array();
if($BSONfield == "_id"){
$sdata = new MongoID($sdata);
unset($document["_id"]);
}
$filter = array($BSONfield=>$sdata);
foreach ($document as $k => $v) {
if (is_array($v)) {
foreach ($v as $sk => $sv) {
$secureInnerDocument[$sk] = Security::secureQuery($sv);
}
$secureDocument[$k] = $secureInnerDocument;
}else{
$secureDocument[$k] = Security::secureQuery($v);
}
}
$dbcollection->update($filter,array('$set'=>$secureDocument));
$objid = (string) $secureDocument['_id'];
return $objid;
}
It translates fairly directly:
db.collection.update(
{fieldNameFilter:'filterValue'},
{$set: {'stringFieldName' : 'newValue'}}
);
Translates to:
$collection->update(
array('fieldNameFilter'=>'filterValue'),
array($set => array('stringFieldName'=>$value))
);
Then there are some flags for multi-row updates, etc. which I'm not showing here, but which are in the PHP and Mongo docs.
You might also want to look at: MongoDB - help with a PHP query
So after fiddling around with is my solution ended up being kind of janky, I deleted the Document then re-create it. Here is the code in case anyone is looking:
/**
* updates document in the collection.
* This function secures the data
*
* #return object ID
* #param string $collection The name of the collection
* #param string $BSONfield The $BSON Field you want to index by
* #param string $document The document contents as an array
*/
Public Static function updateDocument($collection, $BSONfield, $document){
$db = Database::dbConnect();
$collection = Security::secureQuery($collection);
$BSONfield = Security::secureQuery($BSONfield);
$dbcollection = $db->selectCollection($collection);
if(array_key_exists('_id', $document)){
$document["_id"] = new MongoID($document["_id"]);
}
Database::deleteDocument($collection, $BSONfield, $document);
$objid = Database::createDocument($collection, $document);
return $objid;
}
/**
* Deletes a document in the collection.
* This function secures the data
*
* #return Boolean True - if successfully deleted, False if document not found
* #param string $collection The name of the collection
* #param string $BSONfield The $BSON Field you want to index by
* #param string $document The document contents as an array
*/
Public Static function deleteDocument($collection, $BSONfield, $document){
$db = Database::dbConnect();
$collection = Security::secureQuery($collection);
$BSONfield = Security::secureQuery($BSONfield);
$exists = False;
$dbcollection = $db->selectCollection($collection);
$documentList = $dbcollection->find();
$sdata = $document[$BSONfield];
if($BSONfield == "_id"){
$sdata = new MongoID($sdata);
}
foreach ($documentList as $doc) {
$documentID = $doc[$BSONfield];
if ($documentID == $sdata){
$exists = True;
}
}
if ($exists){
$deleted = True;
$filter = array($BSONfield=>$sdata);
$dbcollection->remove($filter,true);
}else{
$deleted = False;
}
return $deleted;
}
/**
* Inserts document into the collection.
* This function secures the data
*
* #return object ID.
* #param string $collection The name of the collection
* #param string $document The document contents as an array
*/
Public Static function createDocument($collection, $document){
$db = Database::dbConnect();
$collection = Security::secureQuery($collection);
$dbcollection = $db->selectCollection($collection);
$secureDocument = array();
$secureInnerDocument = array();
foreach ($document as $k => $v) {
if (is_array($v)) {
foreach ($v as $sk => $sv) {
$secureInnerDocument[$sk] = Security::secureQuery($sv);
}
$secureDocument[$k] = $secureInnerDocument;
}else{
if ($k == '_id'){
$secureDocument[$k] = $v;
}else{
$secureDocument[$k] = Security::secureQuery($v);
}
}
}
$dbcollection->insert($secureDocument);
$objid = (string) $secureDocument['_id'];
return $objid;
}
and how i am securing all the data from injections:
/**
* Secures string to be inputed into a database.
*
* #return Retuns secure string
* #param String $string String to be secured
*/
Public Static Function secureQuery($string){
$secureString = strtr($string, array(
"'" => "0x27",
"\"" => "0x22",
"\\" => "0x5C",
"<" => "0x3C",
">" => "0x3E",
"=" => "0x3D",
"+" => "0x2B",
"&" => "0x26",
"{" => "0x7B",
"}" => "0x7D",
));
return $secureString;
}
/**
* Un-Secures string to be inputed into a database.
*
* #return Retuns unsecure string
* #param String $string String to be un-secured
*/
Public Static Function unsecureQuery($string){
$secureString = strtr($string, array(
"0x27" => "'",
"0x22" => "\"",
"0x5C" => "\\",
"0x3C" => "<",
"0x3E" => ">",
"0x3D" => "=",
"0x2B" => "+",
"0x26" => "&",
"0x7B" => "{",
"0x7D" => "}",
));
return $secureString;
}
enjoy!
You don't seem to be using the $set operator correctly. As per the MongoDB docs, you need to format your update document like so;
{ $set : { field : value } }
If you're running a $set on nested keys, you need to use dot notation to get to them. For example;
{ $set : { field.nest : value } }
I am using this code to export selected data from MySQL to CSV using PHP, I am facing a little problem that when data exported to the csv file it looks like below:
First line in its correct place, but starting from the second row data shifts to the right one space, if I open the csv file in Excel, I can see the most left cell after the first row is empty.
parts destination
===================
1 9.71504E+11
1 9.71504E+11
1 96656587662
1 9.71504E+11
This is my code :
$values =mysql_query( "SELECT parts,destination from log");
$rown = 0;
$row = array();
$row[] = 'parts';
$row[] = 'destination'."\n";
$data .= join(',', $row)."\n";
while( $row_select = mysql_fetch_assoc($values) ) {
if($rown++==0)
$row = array();
$row[] = $row_select['parts'];
$row[] = $row_select['destination']."\n";
}
$data .= join(',', $row)."\n";
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: text/csv");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $data;
exit();
Would you please help?
Regards,
First line in its correct place, but starting from the second row data shifts to the right one space, if I open the csv file in Excel, I can see the most left cell after the first row is empty.
I've found out the hard way that writing CSV is more complex than one would imagine. Take, for example, escaping the values so that the delimiter is properly escaped inside values. I've created a simple class that utilises fwritecsv( ) instead of trying to render CSV myself:
EDIT: I've changed the example to your usage scenario.
<?php
/**
* Simple class to write CSV files with.
*
* #author Berry Langerak <berry#ayavo.nl>
*/
class CsvWriter {
/**
* The delimiter used. Default is semi-colon, because Microsoft Excel is an asshole.
*
* #var string
*/
protected $delimiter = ";";
/**
* Enclose values in the following character, if necessary.
*
* #var string
*/
protected $enclosure = '"';
/**
* Constructs the CsvWriter.
*/
public function __construct( ) {
$this->buffer = fopen( 'php://temp', 'w+' );
}
/**
* Writes the values of $line to the CSV file.
*
* #param array $line
* #return CsvWriter $this
*/
public function write( array $line ) {
fputcsv( $this->buffer, $line, $this->delimiter, $this->enclosure );
return $this;
}
/**
* Returns the parsed CSV.
*
* #return string
*/
public function output( ) {
rewind( $this->buffer );
$output = $this->readBuffer( );
fclose( $this->buffer );
return $output;
}
/**
* Reads the buffer.
* #return type
*/
protected function readBuffer( ) {
$output = '';
while( ( $line = fgets( $this->buffer ) ) !== false ) {
$output .= $line;
}
return $output;
}
}
/**
* Example usage, in your scenario:
*/
$values = mysql_query( "SELECT parts,destination from log" );
$csv = new CsvWriter( );
$csv->write( array( 'parts', 'destination' ) ); // write header.
while( $line = mysql_fetch_assoc( $values ) ) {
$csv->write( $line );
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: text/csv");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv->output( );
exit();
Like #ChrisPatrick points out, the line
$data .= join(',', $row)."\n";
is causing the problem, you should move this to inside the while loop and then you'll get rid of the cell skipping.
The problem is in the following line
$data .= join(',', $row)."\n";
You're concatenating all the elements in $row with commas. So the destination of one row is concatenated with the parts of the next row with a comma in between, so you get something like this:
$data = $row_select['parts'] . ',' . $row_select['destination']."\n" . ',' . $row_select['parts'] etc...
The comma after the newline creates an empty cell at the beginning of the row.
UPDATE It should work with the following
while( $row_select = mysql_fetch_assoc($values)){
$row = array();
$row[] = $row_select['parts'];
$row[] = $row_select['destination']."\n";
$data .= join(',', $row);
}