<?php
Here are three header files that must exist in order to export the database data to an Excel table;
Set encoding
Header (' content-type:text/html; Charset=utf-8 ');
Set to Excel
Header ("Content-type:application/vnd.ms-excel");
Set Excel table name
Header ("Content-disposition:filename=php_est.xls");
Process-oriented, connected database case
$conn = Mysqli_connect ("localhost", "root", "" "," php_test ");
Determine if the connection database is successful
if (Mysqli_connect_error ($conn)) {
Die ("Connection failed:". Mysqli_connect_error ());
}
Read data from MySQL database, set encoding
Mysqli_query ($conn, "SET NAMES utf8mb4");
$sql = "SELECT * from Zrzf_student";
Execute SQL statement
$conn->query ($sql); Here query is the method of the instance object;
$result = $conn->query ($sql);
Add Table header here
$filename = Array ("User ID", "name", "Age", "height");
foreach ($filename as $key = = $value) {
Convert from UTF8 to gb2312 to prevent the export of Excel file character garbled problem
$name = mb_convert_encoding ($value, "gb2312", "utf-8");
echo $name. " \ t ";
}
Excel table Wrapping
echo "\ n";
if ($result->num_rows > 0) {
Associative arrays
while ($row = Mysqli_fetch_array ($result, mysqli_num)) {
Save data
$DATAARR [] = $row;
echo $row [0]. " \ t ". $row [1]." \ t ". $row [2]." \ t ". $row [3]." \t\n ";
}
}else{
echo "No query data!";
}
$conn->close ();
PHP native export Excel file from database