PHPExcel file could be corrupted or unsafe - php

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

Related

CSV export prints complete HTML

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>&copy 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.

Not generating and downloading HTML table data in CSV file in PHP with "header already added" error

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";
?>

How to convert dynamic php file which accepts data from database to pdf?

I am working on WordPress website. And on front-end I am giving the functionality to create a resume online & on submitting the form he will get a option to download & print the resume in PDF format. Till now everything is working fine If I am passing a simple html file to convert into PDF. But I want to create a PDF out of the fields of resume inserted in the database. If I am passing the plain html file for conversion it works fine.
But what if I want to create a dynamic PDF file of the PHP file.
Here is my tried code:
I have used html2pdf conversion library for this.
This is a file from which the call to test.php goes.
require("html2pdf/html2fpdf.php");
$htmlFile = "test.php";
$buffer = file_get_contents($htmlFile);
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');
And the test.php file is:
<html>
<body>
<?php
$username = "";
$password = "";
$hostname = "";
$dbname = "";
// Create connection
$con = mysqli_connect($hostname, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo $result = mysqli_query($con,"SELECT * FROM wp_resume ORDER BY id DESC LIMIT 1");
echo "hioooooo";
while($row = mysqli_fetch_array($result))
{
?>
<div>
<label>First Name</label><script type="text/php"><?php echo $row['firstName']; ?></script><br>
<label>Last Name</label><script type="text/php"><?php echo $row['lastName']; ?></script><br>
</div>
<?php
}
?>
</body>
</html>
Now after submitting the form I am getting a PDF file which contains only this data:
First Name
Last Name
And I want all the details of the entry inserted. Clearly this ignores the code inside the <?php ?> tags. So even if I used var_dump(), I didn't get anything.
SO please help me out in this guys. How can I pass the PHP data to PDF file.
Hey I got the solution for this. And the correct code is:
require("html2pdf/html2fpdf.php");
$html = '<h2>Resume</h2>';
$query = "SELECT * FROM wp_resume order by id desc limit 1";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$html .= '<div>
<label>First Name</label> '. $row['firstName'].'<br>
<label>Last Name</label> '. $row['lastName']. '<br>
</div>';
}
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($html);
$pdf->Output('test.pdf', 'F');
I hope this will help somebody....
file_get_contents returns the content of a file, without it being parsed as PHP...
Replace
$buffer = file_get_contents($htmlFile);
With
ob_start();
include($htmlFile);
$buffer = ob_end_clean();
What we are doing: opening an output buffer (this prevents the echo from going to the client as they appear) then we include the PHP file so it gets parsed and all. Remember all the echo's are in the output buffer, so grab it with ob_end_clean() and use the generated HTML to make a PDF.

php file not opening on my new laptop

I have this form that pops up in a modal window like so:
<?php
error_reporting(0);
require("../codebase/grid_connector.php");
include '../site_globals/dbc.php';
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
//Get All Submission ID's for this popup
$datum = array();
$result = mysql_query("SELECT submission_id FROM submissions WHERE submissions.category='$array' AND submissions.manufacturer_id='$array1'");
while ($rowd = mysql_fetch_array($result, MYSQL_ASSOC)) {
$datum[] = $rowd['submission_id'];
}
$datalist = implode($datum, ' , ');
$datalist = filter($datalist);
// Use Submission ID's to Get All Image ID's for this popup
$datum9 = array();
$datasql = mysql_query("SELECT DISTINCT image_id FROM imagsub WHERE submission_id IN ($datalist)");
while ($row23 = mysql_fetch_array($datasql, MYSQL_ASSOC)) {
$datum9[] = $row23['image_id'];
}
$datalist2 = implode($datum9, ' , ');
$datalist2 = filter($datalist2);
//Select filenames from images table that matches $datalist2 results
$sql = "SELECT * FROM images WHERE image_id IN ($datalist2)";
$resultz = mysql_query($sql);
?>
<html>
<head>
<title>Supplychex Vendor Dashboard</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body onLoad="doInitGrid();" marginwidth="0"; topmargin="0">
<div style="width:100%; height:120px; background-image:url(../images/header.png)">
<div style="float:left; width:30%; text-align:center">
<form action="../php/pop_category_viewimages.php" method="post" name="MyForm" target="_blank" id="MyForm">
<fieldset>
<legend>Attachments</legend>
<SELECT id="dropdown" name="dropdown" style="width:250px">
<?php
while ( $rowg = mysql_fetch_array($resultz, MYSQL_ASSOC) ){
echo '<OPTION value="'.$rowg['image_id'].'">'.$rowg['filename'].'</OPTION>'."\r\n";
}
?>
</SELECT></br></br>
<INPUT type="SUBMIT" name="SUBMIT" value="View">
</fieldset>
</form>
</div>
</body>
</html>
I have this action for this form set to this file:
<?php
define("DB_HOST", ""); // set database host
define("DB_USER", ""); // set database user
define("DB_PASS", ""); // set database password
define("DB_NAME", ""); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$id = $_POST['dropdown'];
$query = sprintf('select * from images where image_id = %d', $id);
$result = mysql_query($query);
$image = mysql_fetch_array($result);
header('Content-type: ' . $image['mime_type']);
header('Content-length: ' . $image['file_size']);
echo $image['file_data'];
?>
I currently have a gif file and pdf file in the dropdown. Both gif and pdf work great on my desktop in all browsers. A new tab opens and displays either one. I just picked up a new laptop and eventhough Im using firefox 9 in both places when I run this on my laptop instead of simply displaying the pdf in a new tab the browser tries to download the pop_category_viewimages.php file. In IE on my laptop a new tab opens up blank. In chrome on my laptop the pdf opens up just fine. The gif opens fine in all browsers in all locations. Im totally thrown by this and hoping there is something I can adjust in my code to have the pdf open correctly in all browsers.
It means you do not have a PDF reader installed. Chrome is the only browser (AFAIK) that has a PDF renderer built-in. Other browsers delegate this task to third party software like Adobe's Acrobat Reader, which provide plugins that allow PDFs to be rendered directly in the browser. Lacking such available plugins, the only thing the browser knows what to do is to offer the file for download.
Set the content-disposition header to inline (to ask the browser to show it) or attachment (to ask the browser to download it to disk):
header('Content-Disposition: inline"');
Or
header('Content-Disposition: attachment; filename="downloaded.pdf"');
php file is server dependent, you may need to either configure your IIS, or install wamp or xamp to get the functionality your looking for.

Use php for Output Buffering and jQuery to send ob_get_contents

I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.

Categories