Allow user to save html table locally to csv, PHP & javascript - php

EDITED:
Problem: I have a dynamically-generated html table on a page that I want the user to be able to click a button and download to their computer.
Setup: file called main.php which contains all processing, variables, arrays, etc. => feeds all data into webpages, one of which is table.php (this page dynamically echoes one of the arrays from main.php into an html table) => link in table.php to tblProcess.php with the headers that outputs the file for download.
code I have now in tblProcess.php file that works
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies
outputCSV(array(
array("name 1", "age 1", "city 1"),
array("name 2", "age 2", "city 2"),
array("name 3", "age 3", "city 3")
));
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row); // here you can change delimiter/enclosure
}
fclose($output);
}
link in table.php to tblProcess.php
<a id="dl" href="downloadProcess.php">Download</a>
with that dummy data array in the file, when you click the link all works as expected and it asks you to download filename.csv (with the dummy data in it) so I know the code is fine.
The big issues I'm having is how to get my html table from table.php into this file. Posting it via ajax and retrieving via $_POST hasn't worked at all no matter how I try, but I can't figure out how else to get this table into this file?
the way the table is echoed dynamically in table.php (from an array included from main.php)
echo "<div id='assnTable'><table id='assign' border='1px'>";
echo "<thead><th>uniqueID</th><th>Name</th><th>FundCode</th><th>Amount $</th><th>FundCode</th><th>Amount $</th><th>Totals:</th></thead>";
$count = 1;
echo "<tbody>";
foreach($assn as $unID => $asnm) {
oddClass($count);
echo "<td>{$unID}</td>";
echo "<td>";
echo $stu[$unID]['USER_LAST_NAME'].", ".$stu[$unID]['USER_FIRST_NAME'];
echo "</td>";
foreach($asnm as $fund => $amt) {
echo "<td>{$fund}</td>";
echo "<td class='sumCell'>{$amt}</td>";
}
$count++;
echo "</tr>";
}
echo "<tr class='totalRow'><td></td><td></td><td></td><td></td><td></td><td id='last'><b>Total:</b></td></tr>";
echo "</tbody></table></div>";
In closing, my big question is, HOW do I get this html table into the processing file that downloads the file? I can clean and prepare it into an array or whatever I need, I just can't figure out how to get it into the other file. Trying to link an ajax post to the clicking of the download link disables the download part of it.
Thanks!

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.

Jump to Another Page After Generate Excel File in PHP

I'm making a form (form.php) for user to insert data, after user finish inserting data, form action will jump to formGenerateXLS.php (using POST method) for generate user data to XSL file. In the bottom of formGenerateXLS.php I put a javascript code to jump to dashboard (home.php) but it fail. The Excel file successfully generate but javascript code not working. How to work with that?
if(isset($_POST['issue_time'])){
$product_desc = $_POST['product'];
$filename_excel = date("Ymd_")."$product_desc";
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=$filename_excel.xls");
echo "<table border='1'>";
echo "<tr>";
echo "<th colspan='3' bgcolor='#1bf3b3'>New Ticket Request</th>";
echo "</tr>";
echo "<tr>";
echo "<td>Name</td>";
echo "<td></td>";
echo "<td>User</td>";
echo "</tr>";
echo "</table>"
}
echo "<script>window.location='home.php'</script>";
Because echo does not execute the command, but simply writes it to the file.
In order to reposition a php file, use the header () function, for example header ('location: home.php');.

fail to geting xml data with $_SESSION condition

i am trying to get xml data from my website. with this code
$xml=simplexml_load_file('http://www.mywebsite.com/dataxml.php');
foreach ($xml->id as $id) {
echo "<tr>";
echo "<td>".$id->phone."</td>";
echo "<td>".$id->first_name." ".$id->last_name."</td>";
echo "<td>".$id->update."</td>";
echo "</tr>";
}
it work fine with below code in website file dataxml.php
header('Content-Type: text/xml');
include_once('customer.php');
$ThisCustomer = new Customer_Info;
echo $ThisCustomer->xmlCustomers();
but when i am trying to get with below code i get error.
session_start();
if(!isset($_SESSION['authorize'])) return;
// if i place this line before/after header result is same
header('Content-Type: text/xml');
include_once('customer.php');
$ThisCustomer = new Customer_Info;
echo $ThisCustomer->xmlCustomers();
Warning: simplexml_load_file(): http://www.mywebsite.com/dataxml.php:1: parser error : Document is empty in C:\wamp\www\xml_show.php on line 29
also note:
if i visit direct site with 2nd code like http://www.mywebsite.com/dataxml.php it does display xml data correctly.

Dynamically generated XML File Doesn't work on Server but works well on localhost

I generated a XML file in php. This file generates a xml output perfectly in my localhost and at the same time when I uploaded it to my server it fails.
Error Screen
Here is the code.
<?php
include_once("database/db.php");
$sqlNews = "SELECT * FROM news";
$runSqlNews = mysql_query($sqlNews);
while ($rowSqlNews = mysql_fetch_array($runSqlNews))
$arrSqlNews[] = $rowSqlNews;
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
for($i=0;$i<count($arrSqlNews);$i++)
{
echo "<news>";
echo "<newsId>".$arrSqlNews[$i][id]."</newsId>";
echo "<newsAuthor>".$arrSqlNews[$i][news_author]."</newsAuthor>";
echo "<description>".$arrSqlNews[$i][news_description]."</description>";
echo "<newsText> <![CDATA[".$arrSqlNews[$i][news_text]. "]]></newsText>";
echo "<plainNewsDescription>".$arrSqlNews[$i][plain_news_description]."</plainNewsDescription>";
echo "<plainNewsTitle>".$arrSqlNews[$i][plain_news_title]."</plainNewsTitle>";
echo "<newsUrl> <![CDATA[". $arrSqlNews[$i][news_url]. "]]></newsUrl>";
echo "<newsCategory> <![CDATA[". $arrSqlNews[$i][category]. "]]></newsCategory>";
echo "<image>http://metroplots.com/images/members/".$arrSqlNews[$i][news_image]."</image>";
echo "<createdOn>".$arrSqlNews[$i][created_on]."</createdOn>";
echo "</news>";
}
echo '</xml>';
?>
New xml File after changes
<?php
ini_set('error_reporting', E_ALL);
include_once("database/db.php");
$dbConn = new mysqli($dbHost, $dbUserName, $dbUserPasswrd, $database);;
$sqlNews = "SELECT id, news_author,news_description,
news_text, news_url, category, news_image, created_on
FROM news";
$stmt = $dbConn->prepare($sqlNews);
$stmt->execute();
$stmt->bind_result($id, $newsAuthor, $newsDescription, $newsText, $newsUrl, $Category, $newsImage, $createdOn);
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
echo "<news>";
while($stmt->fetch())
{
echo "<newsId>".$id."</newsId>";
echo "<newsAuthor>".$newsAuthor."</newsAuthor>";
echo "<description>".$newsDescription."</description>";
echo "<newsText> <![CDATA[".$newsText. "]]></newsText>";
echo "<newsUrl> <![CDATA[". $newsUrl. "]]></newsUrl>";
echo "<newsCategory> <![CDATA[". $Category. "]]></newsCategory>";
echo "<image>http://metroplots.com/images/members/".$newsImage."</image>";
echo "<createdOn>".$createdOn."</createdOn>";
}
echo "</news>";
echo '</xml>';
$stmt->close();
$dbConn->close();
?>
Please let me know where I went wrong. Thanks in Advance !!!
Hard to say what exactly goes wrong here.
For debugging, you could add a ini_set('error_reporting', E_ALL); at the beginning of your script or watch your php error log.
You got a few other problems in your script architecture
You should no longer use the mysql extension. Use mysqli or PDO instead.
The headers should be sent once only. Move them out of your loop to the top
why do you loop through the result twice? Remove the for loop and move its content into the while loop. Within the loop replace the variable $arrSqlNews by $rowSqlNews and remove the index accessor [$i]
Simplified example
while( $rowSqlNews = mysqli_fetch_assoc( $mysqliResult ) )
{
echo $rowSqlNews['yourdbCol1'];
}
Have you tried disabling PHP Output Buffering?
In PHP.ini: output_buffering = Off or comment out existing setting: ;output_buffering = On.
Don't forget to restart web server after changing settings.
I suspect that your upload tool transfers the file not in binary-safe way. Try to compare file sizes of the copy on your local machine and the remote one.

displaying an image saved as a Blob in a MySql DB

Im creating a blog and the little bit of code below is where the blog geets printed out.
I've got a blob saved in my mysql database and im trying to turn it back into an image.
the imageName, imageType, imageSize, imageContect all receive values when i run my code. The problem is that the imageContent variable displays a load of random characters rather then an image. it seems that the reason for this is the headers but i've no idea what to do. can anyone help me to recode the image. thanks
while($row = mysql_fetch_array($result))
{
echo "name ".$row['imageName'].'<BR>';
echo "type ".$row['imageType'].'<BR>';
echo "size ".$row['imageSize'].'<BR>';
echo '<B>'.$row['blogTitle'].'</B><br />';
echo '<A HREF = http://www.alcaeos.com/blog/displayblogProcess.php?mode=edit&blogID='.$row['blogID'].'>Edit</A> ';
echo '<A HREF = http://www.alcaeos.com/blog/displayblogProcess.php?mode=delete&blogID='.$row['blogID'].'>Delete</A><BR />';
echo $row['blog'].'<br />';
header("Content-length:".$row['imageSize']);
header("Content-type:.".$row['imageType']);
header("Content-Disposition: attachment; filename=".$row['imageName']);
echo $row['imageContent'].'---------<br /><br /><br />';
}
Here is a fairly simple example of displaying an image stored as a blob.
<?php
require_once ('./includes/db.inc.php'); // Connect to the db.
//let the browser know its an image
header("Content-type: image/jpeg");
// Make the query.
$query = "SELECT thumbnail FROM items where item_id=" . $_GET['item_id'];
$result = #mysql_query ($query);
if ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo $row['thumbnail'];
}
mysql_close(); // Close the database connection.
?>
Skip the Content-length and Content-disposition, just use Content-type and set it to a valid MIME type.
Assuming they're JPEGs, you'd do this:
header( 'Content-type: image/jpeg' );
Check out this link too

Categories