HTML Table to excel file - php

I have created php coding to generate excel file. data are grab from SQL tables but the result are displayed with the HTML tags to the csv file. please see the attached image file which shows the output of below coding.
//genarate report
$out = '';
$filename_prefix = 'showroom_report';
$filename = $filename_prefix."_".$fromDate."-".$toDate;
$pay_array = array();
$showroom_array = array();
$location_id_array = array();
$pay_sql = "SELECT abans_crm.pay_mode.pay_mode,
Count(abans_crm.customers.purchase_type) AS mode_count,
abans_crm.customers.location_id
FROM
abans_crm.customers
INNER JOIN abans_crm.pay_mode ON abans_crm.customers.purchase_type = abans_crm.pay_mode.mode_id
WHERE
DATE(
abans_crm.customers.purchase_date
) >= '$fromDate'
AND DATE(
abans_crm.customers.purchase_date
) <= '$toDate'
GROUP BY
abans_crm.pay_mode.pay_mode";
$pay_result = mysql_query($pay_sql) or die(mysql_error());
if (mysql_num_rows($pay_result) > 0) {
while($row = mysql_fetch_assoc($pay_result)) {
array_push($pay_array, $row);
array_push($location_id_array, $row['location_id']);
}
}
$location_id_unique = array_unique($location_id_array);
$location_id_result = implode(", ", $location_id_unique);
//load showroom names
$showroom_sql = "SELECT
sh_sso.showrooms.showroom_id,
sh_sso.showrooms.showroom_name
FROM
sh_sso.showrooms
WHERE
sh_sso.showrooms.showroom_id IN ($location_id_result)";
$showroom_result = mysql_query($showroom_sql) or die(mysql_error());
while($row = mysql_fetch_assoc($showroom_result)){
array_push($showroom_array, $row);
}
echo "<table border=1 >\n";
echo "<thead><tr class=\"tableizer-firstrow\"><td colspan=6>Enquiries Report - $fromDate-to-$toDate</td></tr></thead><tbody>\n";
echo " <tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>\n";
echo " <tr><td>SHOWROOM</td><td colspan=4>PAYMENT METHOD</td><td rowspan=2>Total</td></tr>\n";
echo " <tr>"
. "<td> </td>"
. "<td>CASH</td>"
. "<td>CREDIT CARD</td>"
. "<td>HIRE PURCHASE</td>"
. "<td>LEASE</td>"
. "</tr>\n";
$cash_val = 0;
$credit_val = 0;
$hire_val = 0;
$lease_val = 0;
$row_total = 0;
for ($i=0; $i < count($showroom_array); $i++) {
$cash_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Cash');
$credit_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Credit Card');
$hire_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Hire Purchase');
$lease_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Lease');
include_once("../../../includes/sh_cms_functions.php");
$row_total = $row_total + $cash_val;
$row_total = $row_total + $credit_val;
$row_total = $row_total + $hire_val;
$row_total = $row_total + $lease_val;
echo "<tr>"
. "<td>".$showroom_array[$i]['showroom_name']."</td>"
. "<td>".$cash_val."</td>"
. "<td>".$credit_val."</td>"
. "<td>".$hire_val."</td>"
. "<td>".$lease_val."</td>"
. "<td>".$row_total."</td>"
. "</tr>\n";
$row_total = 0;
}
echo "</tbody></table>\n";
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-Encoding: UTF-8");
header("Content-type: text/csv; charset=UTF-8");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;
mysql_close();
}
above coding will generate CSV file.

You have HTML in the output, just simply remove it.

Related

Excel import from mysql table

<?php
require_once("db_connect.php");
$arr = $_GET['arr'];
$selected_header = implode(', ', (array)$arr);
$sql = "SELECT $selected_header FROM release_ ORDER BY id DESC";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=CNC-'.date('Ymd').'.xls');
header('Pragma: no-cache');
header('Expires: 0');
$output = '';
$output .= '<table><tr>';
$header_arr = explode(',', $arr);
$len = count($header_arr);
for($a=0; $a<$len; $a++){
$output .= "<th style='width: 100px; text-align: center;'>" . $header_arr[$a] . "</th>";
}
$output .= '</tr>';
$res = mysqli_query($conn, $sql);
/*====this ruins everything=====*/
while($row = $res->fetch_assoc()){
$output = '<tr align="center">';
for($a=0; $a<$len; $a++){
$output .= "<td>" . $header_arr[$a] . "</td>";
}
echo "</tr>\t\n";
}
/*===============================*/
$output .= '</table>';
echo $output;
?>
I am able to get and display the header in the excel file but the content is not displaying at all. I get the whole string of row tag displayed. How am I able to display the data from the database to excel file. Please help.
I have done in my project(Cakephp) you can use like this own way :-
public function ExportToExcel(){
$users_id = $this->Session->read('selected_user_id');
$this->loadModel('User');
$conditions= array('User.usertype !='=>1);
if(!empty($users_id)){
$ids=explode(",",$users_id);
$conditions = array(
'User.id'=>$ids
);
}
$users = $this->User->find('all',array(
'conditions'=>$conditions,
'order'=>array('User.id Desc')
)
);
ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
$filename = "Users" . date("Y.m.d") . ".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$i = 1;
$row="";
$row_header="S.No."."\t"."Name "."\t"."Email"."\t"."Mobile"."\t"."Address"."\t"."Status"."\n";
if(!empty($users)){
foreach($users as $user){
if($user['User']['status']==1){
$status = "Active";
}
else{
$status = "Inactive";
}
$row .= $i++."\t".$user['User']['firstname'].' '.$user['User']['lastname']
."\t".$user['User']['email']
."\t".$user['User']['phone_number']
."\t".$user['User']['address']
."\t".$status
."\n";
}
}
$this->Session->delete('selected_user_id');
echo($row_header);
echo($row);
die;
}

PHPExcel date formatting in strange numbers

I have made a script using PHPExcel to convert .xls files to .csv files.
The .xls file has date formatting in it, and when converted to .csv the date fields has a high number increasing 1 for every day:
So how do I fix this? I want it to say it like this: 10/Jun or 15/Apr.
My code:
$count = 0;
foreach($html->find('section#content_main a') as $e) {
echo "<h3>" . $e->href . "</h3>";
$link = $e->href;
echo "<p>" . $array[$count] . "</p>";
$file = $array[$count] . ".xls";
file_put_contents($file, fopen($link, 'r'));
if(file_exists($array[$count] . ".csv") == 0){
$fileType = PHPExcel_IOFactory::identify($file);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(false);
for($i = 0; $i < (count($letters) * 2); $i++){
if(i < count($letters)){
}else{
}
}
$objPHPExcel = $objReader->load($file);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()
->setFormatCode('d-mmm');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($array[$count] . ".csv");
$count = $count + 1;
echo "<p>File dosen't exist!</p>";
}else{
echo "<p>File do exist!</p>";
}
}
Thanks for the support on my first post.
I don't know what did the trick but i might think that it was this piece of code:
$objPHPExcel->getActiveSheet()->getStyle('B2:B6')->getNumberFormat()
->setFormatCode('d-mmm');

error on line 2 at column 6: XML declaration allowed only at the start of the document

i have problem in my website in this link :-
http://www.3-hail.com/API/news.php
i get this error message :-
error on line 2 at column 6: XML declaration allowed only at the start of the document
when i try to connect with this file news.php
<?php
require_once("config.php");
$result = mysql_query("select * from newsm WHERE news_id='1' ORDER BY id Desc Limit 30");
while ($row = #mysql_fetch_array($result)) {
$title[] = $row['caption'];
$Image[] = $row['ext'];
$postID[] = $row['id'];
$Textnews[] = $row['text'];
$containing[] = $row['text'];
$post_date[] = $row['date'];
}
function sublen($text,$of,$to){
if(strlen($text) > $to){
echo substr($text,$of,$to)." ...";
}else{
echo $text;
}
}
$count = count($title);
for ( $e = 0; $e <= $count-1; $e += 1) {
}
echo '<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>صحيفة عيون حائل</title>
<link>http://3-hail.com/</link>
<description>صحيفة عيون حائل</description>';
for ( $i = 0; $i <= $count-1; $i += 1) {
$word = array(" ","[/CENTER]","[/JUSTIFY]","[CENTER]","[JUSTIFY]","[email]","[/email]","[/url]","[url]","[B]","[/B]","[IMG]","[/IMG]");
$text = $containing[$i];
$replace = "";
$containingNews = str_replace($word,$replace,$text);
echo '<item>
<title>'.$title[$i] = iconv("windows-1256", "UTF-8", $title[$i]).'</title>
<description>'.$substring = mb_substr($Textnews[$i] = iconv("windows-1256", "UTF-8", $Textnews[$i]),0,100,"utf-8").'...</description>
<containing>'.$containingNews = htmlspecialchars(strip_tags(iconv("windows-1256", "UTF-8", $containingNews))).'</containing>
<link>http://3-hail.com/news.php?action=show&id=' . $postID[$i] . '</link>
<enclosure>http://3-hail.com/contents/newsm/' . $postID[$i] . '.' . $Image[$i] . '</enclosure>
<enclosurem>http://3-hail.com/contents/newsm/' . $postID[$i] . '.' . $Image[$i] . '</enclosurem>
<bubdate>' . date('H:i d-m-Y', $post_date[$i] ) . '</bubdate>
</item>';
}
echo'</channel>
</rss>';
?>

Looping through every record from database

I've searched on the internet for this, and questions here on SO but mostly are using something else than PHP. So i will ask my own question.
What i need to do is make a button that will print out (read literally print, as in downloading a word document with all details on it) every record from the database.
The ID is named 'abstract_id'.
What i'm going to show you next is the print button from all pages, what i mean by this is if you click on said button it will print everything from that specific page:
$abstract_id = addslashes($_POST['abstract_id']);
//Here i connect to the database//
$query = "SELECT * FROM abstracts WHERE abstract_id = '$abstract_id'";
$result = mysql_query($query);
$i = 0;
$title = mysql_result($result,$i,"title");
$author[1] = mysql_result($result,$i,"author1");
$organization[1] = mysql_result($result,$i,"organization1");
$author[2] = mysql_result($result,$i,"author2");
$organization[2] = mysql_result($result,$i,"organization2");
$author[3] = mysql_result($result,$i,"author3");
$organization[3] = mysql_result($result,$i,"organization3");
$author[4] = mysql_result($result,$i,"author4");
$organization[4] = mysql_result($result,$i,"organization4");
$author[5] = mysql_result($result,$i,"author5");
$organization[5] = mysql_result($result,$i,"organization5");
$author[6] = mysql_result($result,$i,"author6");
$organization[6] = mysql_result($result,$i,"organization6");
$format = mysql_result($result,$i,"format");
$language = mysql_result($result,$i,"language");
$presenter = mysql_result($result,$i,"presenter");
$background = mysql_result($result,$i,"background");
$purpose = mysql_result($result,$i,"purpose");
$methods = mysql_result($result,$i,"methods");
$findings = mysql_result($result,$i,"findings");
$conclusion = mysql_result($result,$i,"conclusion");
$word_count = mysql_result($result,$i,"word_count");
$name = mysql_result($result,$i,"name");
$email1 = mysql_result($result,$i,"email1");
$email2 = mysql_result($result,$i,"email2");
$phone1 = mysql_result($result,$i,"phone1");
$phone2 = mysql_result($result,$i,"phone2");
$fax = mysql_result($result,$i,"fax");
$address = mysql_result($result,$i,"address");
$country = mysql_result($result,$i,"country");
$topic = mysql_result($result,$i,"topic");
$master_status = mysql_result($result, $i, "master_status");
$last_edit = mysql_result($result,$i,"last_edit");
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=abstract_" . $abstract_id . ".doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<p><b>PCNE Abstract</b> $abstract_id</p>";
echo "<h1>$title</h1>";
echo "<b>";
for ($i = 1; $i<= 6; $i++) {
echo ((!empty($author[$i-1]) && !empty($author[$i])) ? ", " : "") ;
echo ((!empty($author[$i])) ? $author[$i] . "<sup>" . $i . "</sup>" : "") ;
}
echo ".</b>";
echo "<br>";
for ($i = 1; $i<= 6; $i++) {
if (!empty($author[$i])) {
echo (!empty($organization[$i]) && !empty($organization[$i-1])) ? ". " : "";
echo ((!empty($organization[$i])) ? "<sup>" . $i . "</sup>" . $organization[$i]: "") ;
}
}
echo (!empty($email1)) ? " (" . $email1 . ")" : "";
echo "<br>";
echo "<br>";
echo "<b>Background</b> ";
echo "$background<br>";
echo "<b>Purpose</b> ";
echo "$purpose<br>";
echo "<b>Method</b> ";
echo "$methods<br>";
echo "<b>Findings</b> ";
echo "$findings<br>";
echo "<b>Conclusion</b> ";
echo "$conclusion<br>";
echo "</body>";
echo "</html>";
Now, this works fine, but i need a same working button which does almost the same, but instead of printing out 1 record it should print all. So all i basically need is a foreach or while loop that goes through every abstract_id.
It's been ages since i last programmed php, so i appreciate any help!
If you need any clarification, feel free to ask.
First you don't need your 30 lines of mysql_result, just use mysql_fetch_assoc to get all values in associative array.
Then you just have to do a while ( $line = mysql_fetch_assoc($query) ), see above :
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=abstract_all.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
$query = mysql_query("SELECT * FROM abstracts WHERE 1") or die(mysql_error()) ;
while ( $line = mysql_fetch_assoc($query) )
{
echo "<p><b>PCNE Abstract</b>".$line['abstract_id']."</p>";
echo "<h1>".$line['title']."</h1>";
$authors = Array() ;
for ($i = 1 ; $i <= 6 ; $i++ )
if ( isset($line['author'.$i]) && $line['author'.$i] != '' ) $authors[] = $line['author'.$i].' <sup>'.$i.'</sup>' ;
echo '<b>'.implode(', ',$authors).'</b>' ;
$organizations = Array() ;
for ($i = 1; $i<= 6; $i++)
{
if ( ! isset($line['author'.$i]) || $line['author'.$i] == '' ) continue ; // Check if there is an author, if no go to next loop
if ( isset($line['organization'.$i]) && $line['organization'.$i] != '' ) $organizations[] = ' <sup>'.$i.'</sup> '.$line['organization'.$i] ;
}
echo '<b>'.implode(', ',$organizations).'</b>' ;
echo "<b>Background</b> ";
echo $line['background']."<br>";
echo "<b>Purpose</b> ";
echo $line['purpose']."<br>";
// ...
}
echo "</body>";
echo "</html>";

php report is very slow and crashes in firefox

I have a report that runs and returns 366 records, each containing a thumbnail that is 104 x 80 px. The issue is that the report runs very slowley even though I increased the memory size.
ini_set('memory_limit', '128M');
ini_set('max_execution_time','600');
After writing the SQL query I generate the table items here
generate_table_items($query_all_items);
This then runs through and checks for the image in the columns
function generate_table_items($query){
$columns = array();
$resultset = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$columncount = 0;
$rowcost = 0;
$rowsale = 0;
while ($row = mssql_fetch_assoc($query)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th scope="col" >'.implode('</th><th scope="col" >',get_column_name($columns)).'</th></tr>';
$columncount = sizeof(array_keys($row));
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>',report_image_check($row)).'</td></tr>';
if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$colspan = (count($columns)-2);
echo "<tr><th scope='row'>Documents</th><td colspan='$colspan' >";
$PKID = $row['ID'];
if($row['SumOfTotalCost'] || $row['SumOfSalePrice']){
$rowcost += $row['SumOfTotalCost'];
$rowsale += $row['SumOfSalePrice'];
$get_total = true;
}
$query_docs = mssql_query("select documents.* from dbo.documents where documents.Antiquities_id = $PKID") or die ('get docs query failed ' . mssql_get_last_message());
while($row_docs = mssql_fetch_assoc($query_docs)){
$document = "../documents/" . $row_docs['document'];
echo "<a href='$document' title='opens in a new window' target='_blank' >" . $row_docs['document'] . "</a> | ";
} // End while (list docs)
mssql_free_result($query_docs);
echo "</td></tr>";
myflush();
} // End if all items and all items by value report
} // End While
echo '<tr>';
for($i=0;$i < $columncount-4;$i++){
echo '<td> </td>';
}
echo '<td>Total Cost '. $rowcost.'</td>';
echo '<td>Total Sale '. $rowsale.'</td>';
echo '<td>Total Calculated Difference '. ($rowsale-$rowcost).'</td></tr>';
} // End function
function get_column_name($columns){
$newcol = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$thecount = 0;
foreach($columns as $col) {
if($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
// Don't list the PK
} else {
$newcol[] = '<img id="'.$col.'" src="../images/icons/arrow_down.png" alt="click to sort by" onclick="sortby(\''.$col.'\');" />' . $col;
}
$thecount++;
}
/*if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$newcol[] = "documents";
}*/
return $newcol;
}
function report_image_check($row){
global $base_url, $uploaded_images_folder;
$newrow = array();
$imageext = array();
$imageext[0] = ".jpg";
$imageext[1] = ".png";
$imageext[2] = ".gif";
$imageext[3] = ".tiff";
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$PKID = 0;
$thecount = 0;
foreach($row as $rn) {
if(in_array(strtolower(substr($rn,-4)),$imageext)){
$small_img_ext = substr($rn,-4);
$small_img = substr($rn,0,strripos($rn,"."));
$small_img = $small_img . '_140_105' . $small_img_ext;
$newrow[] = '<a href="' . $base_url . $uploaded_images_folder . '/' . $small_img . '" title="click to zoom on image" target="_blank" ><img src="' . $base_url . $uploaded_images_folder . '/' . $rn . '" alt="" width="50px" height="50px" /></a>';
} elseif($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$PKID = $rn;
} elseif($thecount == 2 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='../index.php?template=10&PKID=$PKID' target='_blank' >$PKID (click to view)</a>";
} else {
$newrow[] = $rn;
}
$thecount++;
myflush();
}
/*if (in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='#&PKID=$PKID' target='_blank' >Documents (click to view)</a>";
}*/
return $newrow;
} // End function
//// Flushing function
function myflush(){
ob_implicit_flush();
ignore_user_abort();
}
Can anyone see an issue with this code or see why it would take so long or why it crashes firefox? Would printing to pdf function work better?
It'll take a long time because you're nesting SQL queries... executing a second SQL query for every result that has been returned by the first query.... Doing a single query with a JOIN should help performance significantly.
Printing to PDF would almost certainly be slower: you'd eithe rneed a lot of code to position everything correctly in the report yourself, or to use one of the libraries that can take HTML and render it to a PDF (as you're already generating HTML anyway at the moment, this would be additional processing)

Categories