I have this export button that needs to xport data fro my database to an excel(csv) file but when i press itthe complete html is shown in the csv file.
here is my ode for the export:
if (isset($_POST["export"])) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('example','example','example','example','example','example','example','example','example','example'));
$query = "SELECT example,example,example,example,example,example,example,example,example,example FROM user";
$stmt = $con->prepare($query);
$stmt->execute();
fclose($output);
exit();
}
Edit:
This is my complete file with the code in it, i tried both options that were given below and they didn't seem to work. It still prints the complete html into a csv file.
<?php
if (isset($_POST["export"])) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('example','example','example','example','example','example','example','example','example','example'));
$query = "SELECT example,example,example,example,example,example,example,example,example,example FROM user";
$stmt = $con->prepare($query);
$stmt->execute();
fclose($output);
exit();
}
print '<div class="dropdown">
<button class="dropbtn">Kies een Lijst... <i class="fa fa-caret-down"></i> </button>
<div class="dropdown-content">
Gehele Lijst
Namen/Social/Soort
Namen & Soort
Soort
Namen & Categorie Bordspellen
Namen & Categorie Bordspellen
Namen
</div>
</div> ';
function getKeys($con, $query)
{
$result = $con->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
return array_keys($row);
}
function getValues($con, $query)
{
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
return $data;
}
$query = "SELECT example,example,example,example,example,example,example,example,example,example FROM user";
//Tabel 1
print "<table id='een'>";
$array_keys = getKeys($con, $query);
print " <tr>";
foreach ($array_keys as $value) {
print " <th>$value</th>";
}
print " </tr> ";
//Values
$data = getValues($con, $query);
foreach ($data as $row) {
print " <tr> ";
foreach ($row as $name => $value) {
print " <td>$value</td> ";
}
print " </tr> ";
}
print '<form method="post" action="index.php?pages=export1"><button type="submit" name="export" value="export" style="width: 5%; height: 5%">Export</button></form>';
//export to csv
print "</table> ";
print '
<footer class="w3-center footer" style="margin-top: 25%">
<div class="w3-xlarge w3-section">
<?php $_SESSION["loggedin"] = true;
if ($_SESSION["loggedin"] === true) {
?>
<h6><br>© Big Bang 2020 Uitloggen</h6>
<?php
}
?>
</div>
</footer>';
Edit 2
maybe it helps that i show the result in the csv file.
csv file:
The header is a header.php file which is included in the index.php file automatically.
If you have other PHP and HTML in your script located earlier than the code shown, then that content will still be output by PHP - everything in the script will be output unless you specifically instruct it not to be. And you've decided to redirect all that output to a file download, so the result is inevitable - all the output goes into the file.
You need to make sure that other content doesn't get output when the user has chosen the export option. This is simple enough:
Either:
Just put the if (isset($_POST["export"])) {
as the first line of the script so that nothing else is output first. The script will already end after that due to your exit() command, so no other output would then be included in the download. (If you also have a header file which outputs HTML included before this, then this option won't be sufficient, you'll need to use the second option below - which is arguably a better separation of concerns anyway.)
OR
put the export code into a separate PHP script which doesn't have any other purpose or function, then there is no danger of other content being accidentally included in the file. Whatever form you are using to request the export should be changed to post back to that script instead.
Related
<title>Orders Export</title>
<body>
<?php
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
$con = mysqli_connect('localhost','suresafe_admin','iwant$100','suresafe_suresafety');
$query = "select * from `orders_approval` where `approve`='1' and `company_name`='GAVL-F111'";
$result = mysqli_query($con,$query);
$output = '';
if(mysqli_num_rows($result) > 0)
{
$output .= '?>
<table class="table" bordered="1">
<tr>
<th>order_no</th>
<th>order_date</th>
<th>order_name</th>
<th>total_amount</th>
</tr><?php
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["order_no"].'</td>
<td>'.$row["order_date"].'</td>
<td>'.$row["order_name"].'</td>
<td>'.$row["total_amount"].'</td>
</tr>
';
}
$output .= '</table>';
}?>
</body>
</html>
The code is simple. Working well in local. But when I use this in my website on server. It shows only table with data. It don't export that data in Excel.
order_no order_date order_name total_amount
100000705 2017-05-07 MR. PRADEEP Y 113500
100000708 2017-05-11 MR. A SRINIVASA RAO 5448
100000725 2017-05-30 MR. A SRINIVASA RAO 77180
Here is the result I can see when I click on export link.
In local server, it is easily exported.
If you had configured your server properly, you would be seeing warnings. You cannot send a header after data has already been output. In addition, the data you're sending is not application/xls (which is not a valid MIME type) it's text/html. You're also outputting "?>" and "<?php" into your HTML, which will not work too well.
However, I would suggest going with CSV for the data you're outputting:
<?php
$con = mysqli_connect("localhost", "suresafe_admin", "iwant$100", "suresafe_suresafety");
$query = "SELECT order_no, order_date, order_name, total_amount from orders_approval WHERE approve = 1 AND company_name = 'GAVL-F111'";
$result = mysqli_query($con, $query);
$output = "";
if(mysqli_num_rows($result) > 0) {
$output .= "order_no,order_date,order_name,total_amount\n";
while($row = mysqli_fetch_assoc($result)) {
$output .= "$row[order_no],$row[order_date],$row[order_name],$row[total_amount]\n";
}
}
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=download.csv");
echo $output;
This is a critical scenario.I have 2 pages such as
output.php has dynamic table data with style which is get from excel.
<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
/* EXCEL TABLE */
$inputFileName2 = 'C:\inetpub\wwwroot\Monthly-EDM\Action_items.xlsx';
try {
$objPHPExcel1 = PHPExcel_IOFactory::load($inputFileName2);
}
catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName2, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
/* Open an Excel & count */
$allDataInSheet = $objPHPExcel1->getActiveSheet()->toArray(null, true, true, true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
$file = fopen($inputFileName2, "r");
fclose($file);
echo '<table width="800" border="0" cellspacing="0" cellpadding="0" align="center">';
echo '<tr>';
echo '</td>';
/* <th> code here */
echo '</td>';
echo ' </tr>';
echo ' <!-- Header blue row - end -->';
echo '<style>.shiva:nth-child(odd) { background-color:#b9b8bb; }</style>';
echo '<style>.shiva:nth-child(even) { background-color:#e5e8e8; }</style>';
for ($i = 2; $i <= $arrayCount; $i++) {
$_SESSION["a"] = trim($allDataInSheet[$i]["A"]);
$_SESSION["b"] = trim($allDataInSheet[$i]["B"]);
$_SESSION["c"] = trim($allDataInSheet[$i]["C"]);
$_SESSION["d"] = trim($allDataInSheet[$i]["D"]);
$_SESSION["e"] = trim($allDataInSheet[$i]["E"]);
$_SESSION["f"] = trim($allDataInSheet[$i]["F"]);
$_SESSION["g"] = trim($allDataInSheet[$i]["G"]);
echo ' <tr>';
echo '<td>';
echo '</td>';
echo ' </tr>';
}
echo '<!-- table content - end --> ';
echo '</table>';
echo '</td>';
echo ' </tr>';
echo '</table>';
?>
get.html (I want to get the output of output.php here)
Click to view the result of the output.php
How to get the output of output.php and pass this output to get.html page and show the output.Is this possible to access the php output from html page??
Thanks in advance.Please help me to fix it.
Here is one solution (this solution assumes you are using Apache)
Create a .htaccess file at the root of your site. Put this in the .htaccess file:
AddType application/x-httpd-php .html .htm
This file will make Apache parse .html files as PHP. Then in your get.html file, put this code:
<html>
<head></head>
<body><?php include('path/to/output.php'); ?></body>
</html>
If you view the get.html file in your browser, you will see the output of output.php
Here is an alternative solution using Javascript and AJAX:
Put the following code in your get.html file. This will make an ajax request to your output.php file and put the response in a <div id="output"></div>.
<html>
<head></head>
<body>
<div id="output"></div>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'output.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
document.getElementById('output').innerHTML = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
</script>
</body>
</html>
I'm not 100% sure, if this is what you mean. But if you make a file (foo.php) and put it in the same directory as where output.php is, and then add this to foo.php:
<?php
$myfile = fopen("output.php", "r") or die("Unable to open file!");
echo fread($myfile,filesize("output.php"));
fclose($myfile);
?>
Then that should print the content of output.php in your browser, as HTML (if you go to /foo.php in the browser).
Is that it?
Dear Fellow PhP Experts,
I am writing below code to export HTML table data in PHP.
Its working nicely in localhost. However, when I deployed to the domain, there is warning-
'Warning: Cannot modify header information - headers already sent by
(output started at ../result_month.php:64 //dbconnect.php line//) in
../result_month.php on line 77 //header("Location: $FileName") line//'.
Seeking suggestion from you, what I am exactly doing wrong.
<?php require_once('dbconnect.php'); ?>
<?php
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
?>
<?php //I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
Any content without PHP open tag are treated as HTML, sent as HTTP_BODY.
HTTP_BODY will be sent after HTTP_HEADER was closed.
Try these codes:
<?php
require_once('dbconnect.php');
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
//I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
// WARNING : Uncomment this will cause header() call failed.
//echo "THIS IS HTTP_BODY";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
When I generate an Excel report using PHPExcel I get this error:
"The file format and extension of 'test.xls' don't match. The file
could be corrupted or unsafe. Unless you trust its source, don't open
it. Do you want to open it anyway?"
This is my set up -- PHP 5.4/PHPExcel 1.7.9/Windows 7
When I click 'OK' to open the unsafe excel file anyway it either is empty or gibberish.
HTML Code: it allows the the user to select a report from the drop down then they select the button if they either want to preview the report, generate an excel file, or create a PDF file. But in this case I'm working on getting the excel files to generate.
<!DOCTYPE html">
<html>
<head>
<meta charset=utf-8" />
<title>Generate Reports</title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<!--Display the Criteria screen only if Title Org Codes Report (rpt3) is selected-->
<script type="text/javascript">
function showForm() {
var selopt = document.getElementById("selReport").value;
if (selopt === "rpt3") {
document.getElementById("criteria").style.display = "block";
}
else {
document.getElementById("criteria").style.display = "none";
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="reports" class="center">
<h3> Generate Reports: </h3>
<!--Display the list of reports-->
<form id="frm1" name="frm1" method="post" action="Reports.php">
<!-- Excel, PDF, View buttons -->
<input type="submit" value="Preview Report" id="view" name="view">
<input type="submit" value="Export to Excel" id="excel" name="excel">
<input type="submit" value="Publish as PDF" id="pdf" name="pdf">
<br><br><br>
Select a Report:
<select id="selReport" name="selReport" onclick="showForm();">
<option></option>
<option value="rpt1">Units/Ranges Summary</option>
<option value="rpt2">Divisions Table</option>
<option value="rpt3">Title Codes</option>
</select>
<!--Creates the criteria drop down menu-->
<div id="criteria" style="display:none">
<br><br><h3>Selection Criteria for Reports:</h3>
Title File Status:
<select name="selCriteria" id="selCriteria" onchange="showForm();">
<option></option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
<option value="all">All</option>
</select>
</div> <!--end criteria -->
</form> <!-- end frm1 -->
</div> <!-- end #reports -->
</div> <!-- end #content -->
</div> <!-- end #wrapper -->
</body>
</html>
Here is the PHP file: where the PHPExcel code is executed. I built if else statements to indicate which report the user selected and run only that report.
<?php
//Get the user selection and put into variables
$varRpt = $_POST['selReport'];
$varCrit = $_POST['selCriteria'];
// require the PHPExcel classes
require 'PHPExcel/Classes/PHPExcel.php';
// PHPExcel_Writer_Excel2007
require 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
//-------------------------------
// Connect to the MySQL database
//-------------------------------
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "*******";
$dbname = "test";
mysql_connect($dbhost,$dbuser,$dbpass)or die ("Could not connect to mysql because ".mysql_error());
mysql_select_db($dbname)or die("Unable to select database" .mysql_error());
//-------------------------------------
// Figure out which report to generate
//-------------------------------------
if ($varRpt == "rpt1")
{
$query = "SELECT a.div_id, a.unit_id, b.unit_beg, b.unit_end, a.title_org, c.long_desc, c.short_desc FROM depunits a LEFT OUTER JOIN unitRanges b ON ( a.unit_id )= ( b.unit_id ) LEFT OUTER JOIN orgcodes c ON ( a.title_org )= ( c.l1l5_id ) ORDER BY a.div_id, a.unit_id" ;
//Column headings
$headings = array('Div_id','Unit Id','Unit Begin','Unit End','Title Org','Long Desc','Short Desc');
// Sheet name
$title = "Summary Report Units/Ranges";
// Name of the saved excel file
$filename = "Rpt1_" . date('Ymd') . ".xls";
}
else
if ($varRpt == "rpt2")
{
$query = "SELECT alldiv_id, div_id, L1l2_id, L2_id, L1l3_id, L2l3_id, Exec_beg, Exec_end, Csa_id, Area_id, Area_Desc, Short_Desc, Long_Desc FROM divisions WHERE avail_ind='Y' AND active_ind='Y' ORDER BY alldiv_id ";
// Column Labels
$headings = array('All','Div','L1L2','L2','L1L3','L2L3','Exec Begin','Exec End','CSA','Area Id','Area Desc','Short Desc','Long Desc');
// Report Title
$title = "Divisions Table";
// name of the saved excel file
$filename = "Rpt2_" . date('Ymd') . ".xls";
} // end $varRpt == "rpt2"
else
if ($varRpt == "rpt3")
{
//Column heading
$headings = array('Title Code','Short Title','Long Title','Status');
// Report title
$title = "Title Codes";
// Name of the saved file
$filename = "Rpt3_" . date('Ymd') . ".xls";
if ($varCrit == "active")
{
$query = "SELECT L2l5, Stitl, Ltitl, Status FROM Tl2l5 WHERE UPPER(TRIM(status))= 'A' ORDER BY L2l5";
}
else
if ($varCrit == "inactive")
{
$query = "SELECT L2l5, Stitl, Ltitl, Status FROM Tl2l5 WHERE UPPER(TRIM(status))= 'I' ORDER BY L2l5";
}
else
if ($varCrit == "all")
{
$query = "SELECT L2l5, Stitl, Ltitl, Status FROM Tl2l5 ORDER BY L2l5";
}
}
//-----------------------------------------
// Insert data into Excel Report template
//-----------------------------------------
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Sheet name
$objPHPExcel->getActiveSheet()->setTitle('sheet1');
// Set the default font type (Arial) and the size (10)
$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);
// Set the column headings to row 3 and data to start on row 4
$rowHeadStart = 3;
$rowDataStart = 4;
//Merge Cells for the report titles
$objPHPExcel->getActiveSheet()->mergeCells("A1:T1"); // Report Title
$objPHPExcel->getActiveSheet()->mergeCells("A2:T2"); // Date
//Set Cell Text
$objPHPExcel->getActiveSheet()->setCellValue("A1", $title);
$objPHPExcel->getActiveSheet()->setCellValue('A2', date("m/d/Y"));
//Make Report title bold
$objPHPExcel->getActiveSheet()->getStyle("A1:T1")->applyFromArray(array("font" => array( "bold" => true)));
//Make the date italicized
$objPHPExcel->getActiveSheet()->getStyle("A2:T2")->applyFromArray(array("font" => array( "italic" => true)));
//Make Column headers bold
$objPHPExcel->getActiveSheet()->getStyle("A3:T3")->applyFromArray(array("font" => array( "bold" => true)));
//---------------------------------------------
// Loop through to display the column headings
//---------------------------------------------
$col = 'A';
foreach($headings as $heading)
{
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowHeadStart,$heading);
$col++;
} // end $headings as $heading
//-------------------------------------------------
// Loop through the result set to display the data
//-------------------------------------------------
while ($row = mysql_fetch_row($result))
{
$col = 'A';
foreach($row as $cell)
{
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowDataStart,$cell);
$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
$col++;
} // end $row as $cell
$rowDataStart++;
//-----------------------
// Page/Cell Formatting
//-----------------------
//Set font size for the main report title
$objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->setSize(16);
$objPHPExcel->setActiveSheetIndex(0);
// Left align the entire document
$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
// Set the page orientation to landscape
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
} //end $row = mysql_fetch_row($result)
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="0teste.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit();
?>
A week ago the reports were able to generate using the code above but recently for some reason it's giving me the error that the file could be corrupted or unsafe. My PHPExcel class files are in my project folder so the paths are able to be referenced. I'm unsure how to fix this error.
If anybody could shine some light on this issue I would really appreciate it.
Thank you.
please use
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
instead of
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
I tried and it works.
Thank u
thank's for help. I have problem displaying images retrieving from my database.
I cant see the image when loading image.php in img src or directly from the page. When i display the variable without header('Content-type: image/jpeg'); i can see all the code inside, as i put this line all goes off.
I have a table called TABLE with id, title, img stored as longblob directly uploaded inside phpmyadmin.
Can anyone help me?
index.php
<?php
session_start();
include "admin/include/connection2.php";
$data = new MysqlClass();
$data->connect();
$query_img ="SELECT * FROM table ORDER BY data ASC LIMIT 4";
$post_sql = $data->query($query_img);
if(mysql_num_rows($post_sql) > 0){
while($post_obj = $data->estrai($post_sql)){
$id = $post_obj->id;
$titolo = stripslashes($post_obj->title);
$data_articolo = $post_obj->data;
$immagine = $post_obj->img;
// visualizzazione dei dati
echo "<h2>".$titolo."</h2>";
echo "Autore <b>". $autore . "</b>";
echo "<br />";
echo '<'.'img src="image.php?id='.$post_sql['id'].'">';
echo $id;
echo "<hr>";
}
}else{
echo "no post aviable.";
}
// here is the image.php code
<?php
include "admin/include/connection2.php";
$data = new MysqlClass();
// connect
$data->connetti();
$id = $_GET['id'];
echo $id;
$query = mysql_query("SELECT * FROM articoli_news WHERE id='".$id."'"; //even tried to send id='1' but not working
echo $query;
$row = mysql_fetch_array($query);
echo $row['id']; //correct displaying
$content = base64_decode($query['img']);
header('Content-type: image/jpeg');
echo $content;
?>
Delete all "echo" commands except "echo $content;" because there are also appear in the output, and damage your image.
And use ob_start(); in the begining of the script, and check out your script file not contain any of whitespace characters before or after the php begint and close tags .