I am new to PHP and trying to export some DB data to Excel file as below. But in the output I want the column widths to be adjusted automatically to view the entire content. See the code I am using to export data. I am not using any third party libraries for export.
<?php
require_once("db.php");
$contents="email,time_in,v_id,time_out\n";
$user_query = mysql_query('SELECT * FROM table');
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['email'].",";
$contents.=$row['time_in'].",";
$contents.=$row['v_id'].",";
$contents.=$row['time_out']."\n";
}
// remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
header("Content-Disposition: attachment; filename=Report".date('d-m-Y').".xls");
print $contents;
?>
Is there any way to format the output ?
Related
I have images stored in mssql database . I want to retrieve the data via php and create image file . I have tried numerous possibilities but unable to find any correct solution
Image i have in following format stored in database
0xFFD8FFE000104A46494600010200000100010000FFDB00840001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010
I have tried
$row = mssql_fetch_assoc($result);
$db_img = $row['imgdata'];
$db_img = pack("H" . strlen($db_img), $db_img);
header("Content-Type: image/jpeg");
echo $db_img;
displays black image
Also i have tried
file_put_contents( 'test_image.jpg', $binary_data);
Not Working ....
Also tried ...
imagecreatefromstring("0xFFD8FFE000104A46494600010200000100010000FFDB00840001010101010101010101010101010101010101010101010101010101010101010101010101.........");
For my current assignment I'm trying to store files into the DB and display them. Currently I have no problem storing the files but I can't display them properly. I'm using this in my main form.
<td><a href=getImage.php?id='.$file[0].'" />Resume</a></td>
And this is the query I'm using to get the file out of the DB.
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo "<img src=\"{$row['file']}\" /><br />";
The result is
…³V!µÔ¢ošweöÿZ–îÌèEÈÎpEJ·˜kä€òþòâGas
È*G¨¥vA¤uEN¤S]‰:ñY“iwØ8‡¥e]ØÝGÑ‘øQÍ!«3¨ÄvÙÁu§]zÕÿOã^ssÌuáY7WP“ÔT6Æà™ëâþÊQË!üioe8
9ô5ã?ÛSÇÔ‘RÃ⛘VCBh¹>ϳ=BïÃVwåçÔW#¯|8†ufŠ4ob1PiÞ=q(,>µÐYx®Æ÷¥ò›Ñ5b½äy6«ðÆbͲϡ®fóá–
í„ξ‹’xvîYVEöæ«6§]|²½ýj‡Ï#åËßjv™-k.u\ŠÈ›O–#ó!ЊúÊmcLþ-¹ïšÆÔ4ïkùñE¸ÿ0h±j§‘òù
Ԉ켯íº×ÂÝã/g:»¸âïþ=³-²û?áHÑI3ŒKÙW¨ÍNºŽî-¶_Ã#IÙ¸{Tiû¸>â€3ÿu7#V[àüš‘í•ùT[9\Ó’ª?oçJ©ù…69Ùxß÷¹©ö¼
|ÊOµ°™W##êàÔ²iw®»–uõ5Eíåˆà«ôÅHä¯"‘\PˆÙŽ>ïÖœÖò'¡÷†^Ž#3Sg+ÀéYžt±uBG>=H'ÞB>”À¾7ƒè)É#)åsU×S‰‡R>µ"\£ô4‹é"ç=D/ÿ-
š¦¼ô©àuCó'´‰ Ë7çPëÑ¿Z½åÛÌ>\Mk
&ʱœÒ0ê*#)ÏAV怩#Bd`^):ܲ¯ü*îÛERk†^ù¦CiÃsõ¦
ší¹Îj¬“*øhf﶑¬†CqíH’ëëIæsŒŠÐ{=ÍW{
:dÓ¸aÐœýjXîæCÃA:æ”CŽÿe5iG£}h7I7ßCüê¬8èqP–t<Ò…©£¸MÄúbª¼EM'ÚJš‘oPýôϽHˆ2GµZ¶¾T
H/Ò¢yb“§ò¦R9ÓC6,n...
I'm using images as a sample at the moment but the finished php should eventually allow to display PDF documents. If it's any help I'm using phpmyadmin and MySQLi.
As the comments suggest, storing the file location in the database is much better than storing the file's data in the database. BUT if you need to store the file contents in the database for some reason, there are two methods. One is using the HTML data: URL and the other is having a PHP file as the middle man.
For the PHP Middle Man method, look at the answer above mine where it sets the header information and then echo's the file contents. The file extension doesn't matter since browsers refer to the content-type header instead of file extensions.
For the Data URL method, which can be placed directly in your code easily check out http://en.wikipedia.org/wiki/Data_URI_scheme
<?php
// Array of valid Mime Types, prevents possible XSS methods.
$valid_mimes = array(
'image/png',
'image/gif',
'image/jpeg'
);
// Obtain Mime Type using finfo
// Finfo allows for strings instead of file path
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->buffer($row['file']);
// Check if mime is in our $valid_mimes array
if(!in_array($mime,$valid_mimes)) {
// Handle Error
echo 'Illegal Mime Type: '.$mime;
die();
}
$b64 = base64_encode($row['file']);
echo '<img src="data:'.$mime.';base64,'.$b64.'" />';
?>
You cant output <img src=\ as an output it will corrupt the image file and
Please use getImage.php as a different file to output images or verify that no output is printed before,after or in mid of image else it will corrupt the image.
if(isset($_GET['id'])){
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo $row['file'];
}
I am exporting the results of a query from SQL Server. I half successful in doing it coz I have 1 problem. The HTML codes or interface of the page gets included in the exported .csv file. How do I remove it from the exported file? I have the codes below to give you an idea :)
Also, if you have other tips on how can I improve this thing, like I
want it to be in Excel Format (xlsx), please guide me :)
<html>
<head>
<title>Generate Report</title>
<script>
function MessageBox()
{
alert('Clicked!');
}
</script>
</head>
<body>
<form method='post'>
<input type='date' name='dateStart'> <input type='date' name='dateEnd'>
<input type='submit' name='btnSubmit' onclick='MessageBox()'> <br>
</form>
</body>
</html>";
<?php
include "db.php";
$con = SetConn();
if(isset($_POST['btnSubmit']))
{
header("Content-type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename=Export.csv');
$start = $_POST['dateStart'];
$end = $_POST['dateEnd'];
$user_query = sqlsrv_query($con, "SELECT TOP 100 * FROM [db_nps].[dbo].[survey_report] WHERE (time_stamp >= '$start' and time_stamp <= '$end')");
//While loop to fetch the records
$contents = "it_id, it_site, it_oraclenumber, it_lastname, it_firstname, ttsd_number\n";
while($row = sqlsrv_fetch_array($user_query, SQLSRV_FETCH_ASSOC))
{
$contents.=$row['it_id'].",";
$contents.=$row['it_site'].",";
$contents.=$row['it_oraclenumber'].",";
$contents.=$row['it_lastname'].",";
$contents.=$row['it_firstname'].",";
$contents.=$row['ttsd_number']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
}
?>
You are telling PHP to use everything echoed as the content for your CSV file. Yes, you are doing so after you echo your HTML, but it doesn't matter; it is all processed at the same time.
Let me Explain:
When you use the header() method, you are telling the browser that the content it is receiving is of a certain type. In your case, you are telling it that the content it is to receive is a CSV document that it should download.
It does not matter where header() is placed within the file, as long as it is before the print or readFile statements.
So essentially what your browser is doing is reading the entirety of the page, including the HTML as plain text for a CSV document. Remember that while PHP will process itself in order, the browser receives all of the information from the server at the same time, and since you are telling it to download the document as a CSV, it takes the whole page.
So what do you do?
My advice to you is to put the printing code in a separate external PHP document and link to it, rather than trying to do it on a page that echoes HTML.
I solved the problem.Try to use your code like this
$filename = 'trip_data.csv';
// file creation
$file = fopen($filename,"w");
// output the column headings
fputcsv($file, array('travel date', 'travel time', 'travel from', 'travel to','number of pessengers', 'car type', 'trip status', 'flight number', 'travel price( £ )'));
$query = "SELECT travel_date,travel_time,travel_from,travel_to,number_of_pessengers,car_type_id,trip_status ,flight_number,travel_price FROM trip";
$travelList = $conn->query($query);
while ($rowValue = $travelList->fetch_assoc()) {
fputcsv($file,$rowValue);
}
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/csv; ");
readfile($filename);
// deleting file
unlink($filename);
exit();
I'm new in PHP and i want to saving pdf into database
I would like to know what the best way to save fpdf into database?
I'm using BLOB type just to save the content of pdf but i want to get the file pdf to read into table and see the content when i clicked to the file.
My code to get the content is:
$query = "select nomeUser,email,nomeVoucher,categoria,preco,confirmacao,filePDF
from historico
LIMIT $start, $per_page";
while ($stmt->fetch()) {
if($confirmacao == "a confirmar"){
echo("<tbody >");
echo("<tr><td>$nomeUser</td>");
echo "<td>$email</td>";
echo("<td >$nomeVoucher</td>");
echo("<td >$categoria</td>");
echo("<td>$preco €</td>");
echo("<td>$confirmacao</td>");
filePDF is the name where i save the content of my fpdf
How can i do this?
I have a web page where a user selects the amount of rows to be displayed followed by a button within a form that exports the data to excel.
<form method="post" action="">
<input type="Submit" name="excel" value="Export" class="button">
</form>
I am able to get the data and put it into the excel file with the follwoing
if($_POST['excel']){
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
)
);
//Get the active sheet and assign to a variable
$foo = $phpExcel->getActiveSheet();
//add column headers, set the title and make the text bold
$foo->setCellValue("A1", "Nombre")
->setCellValue("B1", "Paterno")
->setCellValue("C1", "Pkey")
->setCellValue("D1", "Telefono")
->setCellValue("E1", "Ciudad")
->setCellValue("F1", "Used")
->setTitle("Contactos Encuestas")
->getStyle("A1:F1")->applyFromArray($styleArray);
$xlsRow = 1;
foreach ($rows as $column) {
$foo->setCellValue("A".$xlsRow++, $column[2])
->setCellValue("B".$xlsRow++, $column[3])
->setCellValue("C".$xlsRow++, $column[0])
->setCellValue("D".$xlsRow++, $column[1])
->setCellValue("E".$xlsRow++, $column[5])
->setCellValue("F".$xlsRow++, $column[4]);
}
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"ENcuestas_Contactos.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
$phpExcel->disconnectWorksheets();
unset($phpExcel);
}
This kinda works, the issue is that weird text allong with the webpage elements such as buttons and images get put onto the excel file.
What could be the issue?
is there a setting i'm missing?
Found out why I was getting HTML elements in the excel file.
I had the PHP code within the HTML.
Put the PHP Code outside the <html> code and voilà my excel file displayed without any issues.