PHP Excel performance is slow - php

I want to generate an excel sheet which contain some default fields and variable number of comment fields and data related to comment. I want to set specific width and wrap text for comment fields.Righ now I am using this code
$excelObj = new \PHPExcel();
$ews = $excelObj->getSheet(0);
$ews->setTitle('SurveyDetails');
$ews->fromArray($header, ' ', 'A1'); //Write the header from array
$ews->fromArray($content_arr, ' ', 'A2'); // Write the content from array
$header_style = array(
'font' => array('bold' => true,),
'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER),
);
$content_style = array(
'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER),
);
$start_end_columns = $excelObj->setActiveSheetIndex(0)->calculateWorksheetDimension();
preg_match_all('!\d+!', $start_end_columns, $matches);
$numbers = implode(':', $matches[0]);
$columns = explode(":", $numbers);
$header_end_column_no = $columns[1];
$header_start_end = str_replace($header_end_column_no, 1, $start_end_columns); // A1:G1
$ews->getStyle($header_start_end)->applyFromArray($header_style);
$start_end_columns = str_replace("A1", "A2", $start_end_columns); // Start column of content changed A1 to A2
$ews->getStyle($start_end_columns)->applyFromArray($content_style);
$cols = explode(":", $start_end_columns);
$endColmn = $cols[1];
$endColmn = preg_replace('/[0-9]+/', '', $endColmn);
$activeSheetObj = $excelObj->getActiveSheet();
//Set the autosize height for all the cells
$activeSheetObj->getDefaultRowDimension()->setRowHeight(-1);
$this->log(sprintf("Before set hyper link excel projectId : %s, surveyId : %s", $projectId, $survey_id), LogLevel::INFO);
//Set the hyperlink in the path field
$i = 2;
$count = count($content_arr);
foreach ($content_arr as $content) {
$activeSheetObj->getCell('F' . $i)->getHyperlink()->setUrl($content['path']);
$i++;
}
$activeSheetObj->getStyle('G'.'2:'.'G'.$count)->getAlignment()->setWrapText(true);
$this->log(sprintf("After setting hyper link projectId : %s, surveyId : %s", $projectId, $survey_id), LogLevel::INFO);
//Set specific width for the note and comment fields
$activeSheetObj->getColumnDimension('G')->setWidth(35);
$l = 0;
if (strcmp('G', $endColmn) != 0) {
for ($col = 'J'; $col != $endColmn; $col++) {
if ($l % 3 == 0) {
$activeSheetObj
->getColumnDimension($col)
->setWidth(35);
$activeSheetObj->getStyle($col.'2:'.$col.$count)->getAlignment()->setWrapText(true);
}
$l++;
}
$activeSheetObj->getColumnDimension($endColmn)->setWidth(35);
$activeSheetObj->getStyle($endColmn.'2:'.$endColmn.$count)->getAlignment()->setWrapText(true);
}
unset($content_arr);
$this->log(sprintf("After setting width projectId : %s, surveyId : %s", $projectId, $survey_id), LogLevel::INFO);
$writer = \PHPExcel_IOFactory::createWriter($excelObj, 'Excel2007');
//Save to perticular location
$keyname = "videos/Export/" . $projectId . "/" . $fileName;
$writer->save('/home/senchu/Documents/Infrass.xlsx');
But it takes about 3 seconds to complete the process on 10 columns and 400 rows. Is there any way to optimize this code so that to increase the performance. When I tried caching I didn't get much performance improvement.
Instead of iterating each row and setting hyper link like
$activeSheetObj->getCell('F' . $i)->getHyperlink()->setUrl($content['path']);
is there any method to set hyper link from array.so that we can avoid this much number of iterations.

Related

Grouping lines with a specific pattern into one line as a csv text file

I'm writing a parser for text data. I've almost done... but it's turn to be the php script must be working on a server with PHP Version 5.3.13. And there is no way to upgrage. So I try to re-write the script but... I think I broke it. It doesn't work at all.
First here is the source text data that I need to parse:
27 may 15:28 Id: 42 #1 Random Text
Info: 3 Location: Street Guests: 2
(Text header 1) Apple 15
(Text header 2) Milk 2
(Text header 1) Ice cream 4
(Text header 3) Pencil 1
(Text header 1) Box 1
(Text header 2) Cardboard x1
(Text header 3) White x1
(Text header 1) Cube x1
(Text header 1) Phone 1
(Text header 1) Specific text x1
(Text header 1) Symbian x1
Second here is the desired output, the result text file that I need:
42 ; 15:28
Apple ; 15 ; NOHANDLE ; NOHANDLE
Milk ; 2 ; NOHANDLE ; NOHANDLE
Ice cream ; 4 ; NOHANDLE ; NOHANDLE
Pencil ; 1 ; NOHANDLE ; NOHANDLE
Box ; 1 ; Cardboard, White, Cube ; NOHANDLE
Phone ; 1 ; Symbian ; Specific text
NOHANDLE is necessary 'cause it is, as you can see, a CSV file. In order for a CSV to work properly, each line needs to have the same number of columns. So I have to add NOHADLE everytime when there is no "child" strings.
And, finaly, here is the I code I try to get work right way:
<?php
$data = trim(file_get_contents('inbox_file_utf8_clean.txt'));
$all_lines = preg_split("/\r?\n/", $data);
$date_id_line = array_shift($all_lines);
if(!preg_match('/^\d+\s\w+\s(?<time>\d+:\d+)\sId:\s(?<id>\d+).*/', $date_id_line, $matches)) {
trigger_error('Failed to match ID and timestamp', E_USER_ERROR);
}
$output_data = array(
'info' => array(
'id' => $matches['id'],
'time' => $matches['time']
),
'data' => array()
);
$all_text_headers = array_values(preg_grep('/^\s*\(/', $all_lines));
// The first "Text header" is a parent.
// Count the number of leading whitespaces to determine other parents
preg_match('/^\x20*/', $all_text_headers[0], $leading_space_matches);
$leading_spaces = $leading_space_matches[0];
$num_leading_spaces = strlen($leading_spaces);
$parent_lead = str_repeat(' ', $num_leading_spaces) . '(';
$parent = NULL;
foreach($all_text_headers as $index => $header_line) {
array($lead, $item_value) = explode( ") ", $header_line);
array($topic, $topic_count) = array_map('trim',
preg_split('/\s{2,}/', $item_value, -1, PREG_SPLIT_NO_EMPTY)
);
$topic_count = (int) $topic_count;
if($is_parent = ($parent === NULL || strpos($lead, $parent_lead) === 0)) {
$parent = $topic;
}
// This only goes one level deep
if($is_parent) {
$output_data['data'][$parent] = array(
'values' => array(),
'count' => $topic_count
);
} else {
$output_data['data'][$parent]['values'][] = $topic;
}
};
$csv_delimiter = ';';
$handle = fopen('output_file.csv', 'wb');
fputcsv($handle, array_values($output_data['info']), $csv_delimiter);
foreach($output_data['data'] as $key => $values) {
$row = [
$key,
$values['count'],
implode(', ', $values['values']) ?: 'NOHANDLE',
'NOHANDLE'
];
fputcsv($handle, $row, $csv_delimiter);
}
fclose($handle);
?>
Now I stuck... I get this error:
Parse error: syntax error, unexpected '=' in index.php on line 29
you're right you must use array() insted of just [ ]
and the error line
array($lead, $item_value) = explode( ") ", $header_line);
must be like this:
list($lead, $item_value) = explode(') ', $header_line);
and in the next line you must use list ()
i try to make all corrections:
<?php
$data = trim(file_get_contents('inbox_file_utf8_clean.txt'));
$all_lines = preg_split("/\r?\n/", $data);
$date_id_line = array_shift($all_lines);
if(!preg_match('/^\d+\s\w+\s(?<time>\d+:\d+)\sId:\s(?<id>\d+).*/', $date_id_line, $matches)) {
trigger_error('Failed to match ID and timestamp', E_USER_ERROR);
}
$output_data = array(
'info' => array(
'id' => $matches['id'],
'time' => $matches['time']
),
'data' => array()
);
$all_text_headers = array_values(preg_grep('/^\s*\(/', $all_lines));
// The first "Text header" is a parent.
// Count the number of leading whitespaces to determine other parents
preg_match('/^\x20*/', $all_text_headers[0], $leading_space_matches);
$leading_spaces = $leading_space_matches[0];
$num_leading_spaces = strlen($leading_spaces);
$parent_lead = str_repeat(' ', $num_leading_spaces) . '(';
$parent = NULL;
foreach($all_text_headers as $index => $header_line) {
list($lead, $item_value) = explode(') ', $header_line);
list($topic, $topic_count) = array_map('trim',
preg_split('/\s{2,}/', $item_value, -1, PREG_SPLIT_NO_EMPTY)
);
$topic_count = (int) $topic_count;
if($is_parent = ($parent === NULL || strpos($lead, $parent_lead) === 0)) {
$parent = $topic;
}
// This only goes one level deep
if($is_parent) {
$output_data['data'][$parent] = array(
'values' => array(),
'count' => $topic_count
);
} else {
$output_data['data'][$parent]['values'][] = $topic;
}
};
$csv_delimiter = ';';
$handle = fopen('output_file.csv', 'wb');
fputcsv($handle, array_values($output_data['info']), $csv_delimiter);
foreach($output_data['data'] as $key => $values) {
$row = array(
$key,
$values['count'],
implode(', ', $values['values']) ?: 'NOHANDLE',
'NOHANDLE'
);
fputcsv($handle, $row, $csv_delimiter);
}
fclose($handle);
?>

CodeIgniter one query multiple statements

I use CodeIgniter, and when an insert_batch does not fully work (number of items inserted different from the number of items given), I have to do the inserts again, using insert ignore to maximize the number that goes through the process without having errors for existing ones.
When I use this method, the kind of data I'm inserting does not need strict compliance between the number of items given, and the number put in the database. Maximize is the way.
What would be the correct way of a) using insert_batch as much as possible b) when it fails, using a workaround, while minimizing the number of unnecessary requests?
Thanks
The Correct way of inserting data using insert_batch is :
CI_Controller :
public function add_monthly_record()
{
$date = $this->input->post('date');
$due_date = $this->input->post('due_date');
$billing_date = $this->input->post('billing_date');
$total_area = $this->input->post('total_area');
$comp_id = $this->input->post('comp_id');
$unit_id = $this->input->post('unit_id');
$percent = $this->input->post('percent');
$unit_consumed = $this->input->post('unit_consumed');
$per_unit = $this->input->post('per_unit');
$actual_amount = $this->input->post('actual_amount');
$subsidies_from_itb = $this->input->post('subsidies_from_itb');
$subsidies = $this->input->post('subsidies');
$data = array();
foreach ($unit_id as $id => $name) {
$data[] = array(
'date' => $date,
'comp_id' => $comp_id,
'due_date' => $due_date,
'billing_date' => $billing_date,
'total_area' => $total_area,
'unit_id' => $unit_id[$id],
'percent' =>$percent[$id],
'unit_consumed' => $unit_consumed[$id],
'per_unit' => $per_unit[$id],
'actual_amount' => $actual_amount[$id],
'subsidies_from_itb' => $subsidies_from_itb[$id],
'subsidies' => $subsidies[$id],
);
};
$result = $this->Companies_records->add_monthly_record($data);
//return from model
$total_affected_rows = $result[1];
$first_insert_id = $result[0];
//using last id
if ($total_affected_rows) {
$count = $total_affected_rows - 1;
for ($x = 0; $x <= $count; $x++) {
$id = $first_insert_id + $x;
$invoice = 'EBR' . date('m') . '/' . date('y') . '/' . str_pad($id, 6, '0', STR_PAD_LEFT);
$field = array(
'invoice_no' => $invoice,
);
$this->Companies_records->add_monthly_record_update($field,$id);
}
}
echo json_encode($result);
}
CI_Model :
public function add_monthly_record($data)
{
$this->db->insert_batch('monthly_record', $data);
$first_insert_id = $this->db->insert_id();
$total_affected_rows = $this->db->affected_rows();
return [$first_insert_id, $total_affected_rows];
}
AS #q81 mentioned, you would split the batches (as you see fit or depending on system resources) like this:
$insert_batch = array();
$maximum_items = 100;
$i = 1;
while ($condition == true) {
// code to add data into $insert_batch
// ...
// insert the batch every n items
if ($i == $maximum_items) {
$this->db->insert_batch('table', $insert_batch); // insert the batch
$insert_batch = array(); // empty batch array
$i = 0;
}
$i++;
}
// the last $insert_batch
if ($insert_batch) {
$this->db->insert_batch('table', $insert_batch);
}
Edit:
while insert batch already splits the batches, the reason why you have "number of items inserted different from the number of items given" might be because the allowed memory size is reached. this happened to me too many times.

Filling Excel sheet using PHPExcel

I am Trying to fill my Excel sheet with the data i filtered through the methods i have made. For now i am getting a sheet but i only have only one row filled not the other it's not getting the data i provide it though my object
I am trying my sheet something similar to this sheet .
i am trying to write code in this part of code :
public function export($Sets,$disp_filter)
{
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Offic excel Test Document");
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 10,
'name' => 'Verdana'
));
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
$excel_out = array($this->outputSampleName($Sets));
// var_dump($excel_out);
// exit;
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Sample Size and Margin of Error');
$rowCount = 2;
foreach ($excel_out as $key=> $line)
{
$colCount = 'A';
$i=0;
// $line = array($Set['name']);
// $CT = $Set['crossTabs']['base'];
// $Moe = array($CT['sample']['moe']);
foreach($line as $col_value)
{
// var_dump($col_value);
// exit;
$objPHPExcel->getActiveSheet()->setCellValue($colCount.$rowCount, $col_value[$i])
->getStyle($colCount.$rowCount)->applyFromArray($styleArray);
$colCount++;
}
$rowCount++;
$i++;
}
return $objPHPExcel;
}
protected function outputSampleName($Sets)
{
foreach ($Sets as $Set)
{
$CT = $Set['crossTabs']['base'];
$line = array(
$Set['name'],
$CT['sample']['moe'] . '%'
);
$excel_out []= $line;
}
return $excel_out;
}
when i see by var_dump($excel_out)
i have this data structure :
**Please suggest me something how can i get those percentage values in my next row in optimized way.
for now i can only loop through the sample[name] which are (enthusiasts, hunter, new shooters etc. )from that array. **
thanks in advance

Pass array to Excel

I am using (trying to use) PHPExcel to pass an array to excel, I have defined the headings and i want every array in the array to in a separate row.
However, this only puts the headings in the excel file and not the data from the array. What am i doing wrong?How can I get this to work?
Script:
<?php
$databasehost = "localhost";
$databasename = "dummydata";
$databasetable = "import1";
$databasetable2 = "data1";
$databaseusername ="dummydata";
$databasepassword = "dummydata";
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$query = mysql_query("SELECT * from $databasetable;");
$data = array();
$index = 0;
while($row = mysql_fetch_assoc($query))
{
$data[$index] = $row;
$index++;
}
foreach ($data as $key) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$key['latitude'].','.$key['longitude'].'&sensor=true';
$json = file_get_contents($url);
$dataReceived = json_decode($json, TRUE);
//echo '<pre>'; print_r($dataReceived['results']); echo '</pre>';
$compiled = array();
$index = 0;
foreach ($dataReceived['results'] as $value) {
$compiled[$index] = array(
'ref' => $key['id']);
foreach ($value['address_components'] as $value2)
{
$compiled[$index][$value2['types'][0]] = $value2['long_name'];
}
$index++;
}
$sortedData = array();
$index = 0;
foreach ($compiled as $value) {
//echo '<pre>'; print_r($value); echo '</pre>';
$sortedData[$index] = array(
'ref' => $value['ref'],
'lat' => $key['latitude'],
'long' => $key['longitude'],
'route' => $value['route'],
'locality' => $value['locality'],
'administrative_area_level_2' => $value['administrative_area_level_2'],
'administrative_area_level_1' => $value['administrative_area_level_1'],
'country' => $value['country'],
'postal_code_prefix' => $value['postal_code_prefix'],
'postal_town' => $value['postal_town'],
'postal_code' => $value['postal_code'],
'administrative_area_level_3' => $value['administrative_area_level_3'],
'street_number' => $value['street_number'],
'establishment' => $value['establishment'],
);
$index++;
}
echo '<pre>';print_r($sortedData);echo "</pre>";
/*$query = mysql_query("INSERT INTO $databasetable2
ref, lat, long, route, locality, administrative_area_level_2, administrative_area_level_1, country, postal_code_prefix, postal_town)
VALUES
()");*/
}
#mysql_close($con);
/**
* PHPExcel
*
* Copyright (C) 2006 - 2011 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* #category PHPExcel
* #package PHPExcel
* #copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
* #license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* #version ##VERSION##, ##DATE##
*/
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', '1');
date_default_timezone_set('Europe/London');
/** PHPExcel */
require_once 'Classes/PHPExcel.php';
// Create new PHPExcel object
//echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();
// Set properties
//echo date('H:i:s') . " Set properties\n";
$objPHPExcel->getProperties()->setCreator("Anon")
->setLastModifiedBy("Anon")
->setTitle("Crawler Data");
// Add some data
//echo date('H:i:s') . " Add some data\n";
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'ref')
->setCellValue('B1', 'latitude')
->setCellValue('C1', 'longitude')
->setCellValue('D1', 'route')
->setCellValue('E1', 'locality')
->setCellValue('F1', 'administrative_area_level_2')
->setCellValue('G1', 'administrative_area_level_1')
->setCellValue('H1', 'country')
->setCellValue('I1', 'postal_code_prefix')
->setCellValue('J1', 'postal_town')
->setCellValue('K1', 'postal_code')
->setCellValue('L1', 'administrative_area_level_3')
->setCellValue('M1', 'street_number')
->setCellValue('N1', 'establishment');
//$objPHPExcel->getActiveSheet()->fromArray($sortedData, null, 'A2');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Save Excel 2007 file
//echo date('H:i:s') . " Write to Excel2007 format\n";
//!!!!!!!!!!!!!!!!!!!-------- I Change 'Excel2007' to 'Excel5' ------!!!!!!!!!!!!!!!!!!!!!!!!
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//!!!!!!!!!!!!!!!!!!!-------- I Change '.xlsx' to '.xls' ------!!!!!!!!!!!!!!!!!!!!!!!!
$objWriter->save(str_replace('.php', '.xls', __FILE__));
// Echo memory peak usage
//echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";
// Echo done
//echo date('H:i:s') . " Done writing file.\r\n";
?>
file now looks like:
<?php
require_once 'Classes/PHPExcel.php';
date_default_timezone_set('Europe/London');
$databasehost = "localhost";
$databasename = "ryansmur_crawler";
$databasetable = "import1";
$databasetable2 = "data1";
$databaseusername ="ryansmur_admin";
$databasepassword = "Penelope1";
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$query = mysql_query("SELECT * from $databasetable;");
$data = array();
$index = 0;
while($row = mysql_fetch_assoc($query))
{
$data[$index] = $row;
$index++;
}
$headers = array(
'ref', 'lat', 'long', 'route', 'locality', 'administrative_area_level_2',
'administrative_area_level_1', 'country', 'postal_code_prefix',
'postal_town', 'postal_code', 'administrative_area_level_3',
'street_number', 'establishment',
);
$addRowCreate = function(PHPExcel_Worksheet $sheet, $col = 'A', $row = NULL) {
return function(array $data) use ($sheet, $col, &$row) {
if ($row === NULL) {
$row = $sheet->getHighestRow() + 1;
}
$sheet->fromArray(array($data), NULL, "$col$row");
$row++;
};
};
$doc = new PHPExcel();
$doc->getProperties()->setCreator("Anon")
->setLastModifiedBy("Anon")
->setTitle("Crawler Data");
$sheet = $doc->setActiveSheetIndex(0);
$sheet->fromArray($headers);
$addRow = $addRowCreate($sheet);
foreach ($data as $key) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$key['latitude'].','.$key['longitude'].'&sensor=true';
$json = file_get_contents($url);
$dataReceived = json_decode($json, TRUE);
$compiled = array();
$index = 0;
foreach ($dataReceived['results'] as $value) {
$compiled[$index] = array(
'ref' => $key['id']);
foreach ($value['address_components'] as $value2)
{
$compiled[$index][$value2['types'][0]] = $value2['long_name'];
}
$index++;
}
$sortedData = array();
$index = 0;
foreach ($compiled as $value) {
$addRow(array(
'ref' => $value['ref'],
'lat' => $key['latitude'],
'long' => $key['longitude'],
'route' => $value['route'],
'locality' => $value['locality'],
'administrative_area_level_2' => $value['administrative_area_level_2'],
'administrative_area_level_1' => $value['administrative_area_level_1'],
'country' => $value['country'],
'postal_code_prefix' => $value['postal_code_prefix'],
'postal_town' => $value['postal_town'],
'postal_code' => $value['postal_code'],
'administrative_area_level_3' => $value['administrative_area_level_3'],
'street_number' => $value['street_number'],
'establishment' => $value['establishment'],
));
$index++;
}
}
#mysql_close($con);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save(str_replace('.php', '.xls', __FILE__));
echo date('H:i:s') . " Done writing file.\r\n";
?>
Just re-reading your code and it looks rather chaotic. I think it can be improved in many areas, however with the least changes I suggest you do the following:
Instead of first creating multiple arrays of rows you want to add, add a new row each time you have created it. For that you do not even need to name the keys. So before you iterate through the database results, first create the headers (I named it $headers):
$headers = array(
'ref', 'lat', 'long', 'route', 'locality', 'administrative_area_level_2',
'administrative_area_level_1', 'country', 'postal_code_prefix',
'postal_town', 'postal_code', 'administrative_area_level_3',
'street_number', 'establishment',
);
Also before the database iteration, create a helper-function:
$addRowCreate = function(PHPExcel_Worksheet $sheet, $col = 'A', $row = NULL) {
return function(array $data) use ($sheet, $col, &$row) {
if ($row === NULL) {
$row = $sheet->getHighestRow() + 1;
}
$sheet->fromArray(array($data), NULL, "$col$row");
$row++;
};
};
This $addRowCreate helper function will allow you to create a add-row-function later on, like in just a second. Also before the database iteration, create the excel document (memory) and set it's properties. Also add the headers in the first row:
$doc = new PHPExcel();
$doc->getProperties()->setCreator("Anon")
->setLastModifiedBy("Anon")
->setTitle("Crawler Data");
$sheet = $doc->setActiveSheetIndex(0);
$sheet->fromArray($headers);
The next step is to create the add-row-function, which is very easy thanks to the helper above:
$addRow = $addRowCreate($sheet);
You now can use one row after the other by calling it once per row array. For testing purposes, just add another row and save it to disk:
$addRow($headers);
$writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');
$writer->save(basename(__FILE__, '.php') . '.xls');
die('test finished.');
You should now have create the xls file with two rows. You can then remove the test again and inside your loops use the $addRow function:
$addRow(array(
'ref' => $value['ref'],
'lat' => $key['latitude'],
'long' => $key['longitude'],
'route' => $value['route'],
'locality' => $value['locality'],
'administrative_area_level_2' => $value['administrative_area_level_2'],
'administrative_area_level_1' => $value['administrative_area_level_1'],
'country' => $value['country'],
'postal_code_prefix' => $value['postal_code_prefix'],
'postal_town' => $value['postal_town'],
'postal_code' => $value['postal_code'],
'administrative_area_level_3' => $value['administrative_area_level_3'],
'street_number' => $value['street_number'],
'establishment' => $value['establishment'],
));
Technically you can remove the string-array-keys, however I've kept them in so that you can better find the place where you need to change your code as the array already exists there-in.
After you've put this to the work, you can safely remove all the not-any-more-needed temporary arrays and counters.
The full usage-example (test):
require_once 'Classes/PHPExcel.php'; /* PHPExcel <http://phpexcel.codeplex.com/> */
$headers = array(
'ref', 'lat', 'long', 'route', 'locality', 'administrative_area_level_2',
'administrative_area_level_1', 'country', 'postal_code_prefix',
'postal_town', 'postal_code', 'administrative_area_level_3',
'street_number', 'establishment',
);
$addRowCreate = function(PHPExcel_Worksheet $sheet, $col = 'A', $row = NULL) {
return function(array $data) use ($sheet, $col, &$row) {
if ($row === NULL) {
$row = $sheet->getHighestRow() + 1;
}
$sheet->fromArray(array($data), NULL, "$col$row");
$row++;
};
};
$doc = new PHPExcel();
$doc->getProperties()->setCreator("Anon")
->setLastModifiedBy("Anon")
->setTitle("Crawler Data");
$sheet = $doc->setActiveSheetIndex(0);
$sheet->fromArray($headers);
$addRow = $addRowCreate($sheet);
$addRow($headers);
$writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');
$writer->save(basename(__FILE__, '.php') . '.xls');
die('test finished.');
Old Answer:
However, this only puts the headings in the excel file and not the data from the array. What am i doing wrong?
You are actually only storing the headings into the file. You do not store any data.
How can I get this to work?
Bring the array in the right format and uncomment the following line in your code:
//$objPHPExcel->getActiveSheet()->fromArray($sortedData, null, 'A2');
Take care that $sortedData is the needed 2D array, see the examples in this dicsussion:
Array
(
[0] => Array
(
[0] => Relative CellA1
[1] => Relative CellB1
[2] => Relative CellC1
)
[1] => Array
(
[0] => Relative CellA2
[1] => Relative CellB2
[2] => Relative CellC2
)
)
Unless you don't get the array into that kind of 2D format, the function will not work in your favor.
Please let me know if you've got any more questions.
PHPExcel write data to the cell and you must define it position. Just like then you define headers. The principle is that you fill out the document line by line.
So I write example code to show the idea
$alphas = range('A', 'Z'); // A, B, C, D, E...
$sheet = $excel->getActiveSheet();
//headers
$sheet
->setCellValue($alphas[0].'1', 'Title1')
->setCellValue($alphas[1].'1', 'Title2')
->setCellValue($alphas[2].'1', 'Title3')
->setCellValue($alphas[3].'1', 'Title4')
;
$sheet->getColumnDimension($alphas[0])->setWidth(40);
$sheet->getColumnDimension($alphas[1])->setWidth(9);
$sheet->getColumnDimension($alphas[2])->setWidth(60);
$sheet->getColumnDimension($alphas[3])->setWidth(30);
$items = ...;// <--- your data
$row_num = 2; // start from 2 row
foreach($items as $item) {
$sheet->setCellValue($alphas[0].$row_num, $item['key1']);
$sheet->setCellValue($alphas[1].$row_num, $item['key2']);
$sheet->setCellValue($alphas[2].$row_num, $item['key3']);
$sheet->setCellValue($alphas[3].$row_num, $item['key4']);
$row_num++;
}
You can create a generic function to get excel content from any 2D arrays.
PHP array2xlsx function
/**
* This function returns xlsx content from an associative array.
*
* Warning: one cell = about 1k memory, so this function does not work
* if your array is too large.
*
* #param array $array
* #param string $title
* #param string $author
* #return string
*/
function array2xlsx(array &$array, $title = 'New Document', $author = null)
{
// Basic checks
if (count($array) == 0)
{
return null;
}
// Putting meta-data into a new excel file
$ex = new PHPExcel();
$ex->getProperties()->setLastModifiedBy($title);
$ex->getProperties()->setTitle($title);
$ex->getProperties()->setSubject($title);
$ex->getProperties()->setDescription($title);
$ex->getProperties()->setCreator($author);
// Select first page on the excel document
$ex->setActiveSheetIndex(0);
$sheet = $ex->getActiveSheet();
// Writes column titles on row 1 (assuming column names are array keys)
$column_names = array_keys(reset($array));
foreach ($column_names as $column_number => $column_name)
{
$azNumber = PHPExcel_Cell::stringFromColumnIndex($column_number);
$sheet->SetCellValue($azNumber . "1", $column_name);
}
// Writes document content
foreach ($array as $row_number => $row)
{
foreach (array_values($row) as $column_number => $cell_content)
{
// Converts column numbers to alphabetic numbering
$azNumber = PHPExcel_Cell::stringFromColumnIndex($column_number);
$sheet->SetCellValue($azNumber . ($row_number + 2), $cell_content);
}
}
// Creates file contents
$writer = new PHPExcel_Writer_Excel2007($ex);
ob_start();
$writer->save("php://output");
$content = ob_get_contents();
ob_end_clean();
return $content;
}
And send it directly to your user, by sending proper headers.
PHP download_send_header function
function download_send_headers($filename) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
PHP Usage example
// We simulate your array
$array = array();
for ($i = 0; ($i < 50); $i++)
{
$array[$i] = array(
'ref' => "ref {$i}",
'lat' => "lat {$i}",
'long' => "long {$i}",
'route' => "route {$i}",
'locality' => "locality {$i}",
'administrative_area_level_2' => "administrative area level 2 {$i}",
'administrative_area_level_1' => "administrative area level 1 {$i}",
'country' => "country {$i}",
'postal_code_prefix' => "postal_code_prefix {$i}",
'postal_town' => "postal_town {$i}",
'postal_code' => "postal code {$i}",
'administrative_area_level_3' => "administrative area level 3 {$i}",
'street_number' => "street number {$i}",
'establishment' => "establishment {$i}",
);
}
// We send headers and excel content from your array
download_send_headers("my_test.xlsx");
echo array2xlsx($array);
Result

PHP MySQL multiple image URL fields array

In building a website for a friend the database has a row with 39 fields for images.
In the field is the name of the image (e.g. "my_image.jpg") not the image itself (BLOB).
i.e.: image_01, image_02, image_03 and so forth.
I have PHP generating the while loop and getting the information without problems.
I'm trying to get all the images into one array so I can display the pictures from that one row as a gallery.
I hope someone can offer me a way forward as I've tried without success.
from while loop:
$MEDIA_IMAGE_00 = $row["MEDIA_IMAGE_00"];
$MEDIA_IMAGE_01 = $row["MEDIA_IMAGE_01"];
$MEDIA_IMAGE_02 = $row["MEDIA_IMAGE_02"];
I need to echo out as
["propimages/$MEDIA_IMAGE_00", "", "", "$MEDIA_IMAGE_TEXT_00"],
["propimages/$MEDIA_IMAGE_01", "", "", "$MEDIA_IMAGE_TEXT_01"],
["propimages/$MEDIA_IMAGE_02", "", "", "$MEDIA_IMAGE_TEXT_02"]
for them to display in a gallery.
EDIT:
while($row = mysql_fetch_array($sqlSearch)){
$propid = $row["propid"];
$MEDIA_IMAGE_00 = $row["MEDIA_IMAGE_00"];
$MEDIA_IMAGE_01 = $row["MEDIA_IMAGE_01"];
$MEDIA_IMAGE_02 = $row["MEDIA_IMAGE_02"];
$MEDIA_IMAGE_33 = $row["MEDIA_IMAGE_33"];
$MEDIA_IMAGE_34 = $row["MEDIA_IMAGE_34"];
$MEDIA_IMAGE_35 = $row["MEDIA_IMAGE_35"];
}
I'm assuming that $propid is what identifies the row itself and that 'MEDIA_IMAGE_TEXT' is available in the same row:
$properties = array();
while ($row = mysql_fetch_array($sqlSearch)) {
$propid = $row["propid"];
$images = array();
for ($i = 0; $i <= 35; ++$i) {
$imageId = "MEDIA_IMAGE_" . str_pad($i, 2, '0', STR_PAD_LEFT);
if ($row[$imageId]) {
$images[] = array(
$row[$imageId],
'',
'',
$row["MEDIA_IMAGE_TEXT_" . str_pad($i, 2, '0', STR_PAD_LEFT)],
);
}
}
$properties[] = array(
'id' => $propid,
'images' => $images,
);
echo json_encode($properties);
It generates a list of properties, each having an id and an array of images; each image comprises the location (I guess) and the title / description.
Why don't you build an array of images in your while loop ?
$images = array()
$i = 0;
While(...) {
$images[] = $row["MEDIA_IMAGE_0$i"];
$i++;
[...]
}
The you get an array that you ca use in a foreach and display your row(s). On the principle that should work, i think ;)

Categories