PHP native export Excel file from database

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.