Question

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 :)

enter image description here

<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;
}
?>
Was it helpful?

Solution

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.

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top