在项目开辟中,数据导入导出是罕见的须要。PHP作为效劳器端剧本言语,在处理数据导入导出方面存在富强的功能。本文将具体介绍怎样利用PHP实现高效的数据导入导出剧本,包含CSV文件、Excel文件以及数据库数据的导入导出。
起首,须要创建一个HTML表单,用于上传CSV文件。
<form action="do.php?action=import" method="post" enctype="multipart/form-data">
<p>请抉摘要导入的CSV文件:<br/>
<input type="file" name="file" />
<input type="submit" value="导入CSV" />
</p>
</form>
在do.php
文件中,根据上传的CSV文件停止处理。
<?php
include_once "connect.php"; // 连接数据库
$action = $_GET['action'];
if ($action == 'import') {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$sql = "INSERT INTO student (name, sex, age) VALUES ('$data[0]', '$data[1]', '$data[2]')";
mysqli_query($conn, $sql);
}
fclose($handle);
echo "导入成功!";
}
?>
创建一个HTML按钮,用于触发导出操纵。
<form action="do.php?action=export" method="get">
<input type="submit" value="导出CSV" />
</form>
在do.php
文件中,根据恳求导出CSV文件。
<?php
include_once "connect.php"; // 连接数据库
$action = $_GET['action'];
if ($action == 'export') {
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);
$output = "";
while ($row = mysqli_fetch_assoc($result)) {
$output .= implode(",", $row) . "\n";
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
echo $output;
}
?>
起首,须要下载PHPExcel库,并将其包含到项目中。
require_once 'PHPExcel.php';
$objPHPExcel = PHPExcel_IOFactory::load($file);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
foreach ($data as $row) {
$sheet->fromArray($row, null, 'A1');
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('export.xlsx');
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);
$output = "";
while ($row = mysqli_fetch_assoc($result)) {
$output .= implode(",", $row) . "\n";
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
echo $output;
foreach ($data as $row) {
$sql = "INSERT INTO student (name, sex, age) VALUES ('$row[name]', '$row[sex]', '$row[age]')";
mysqli_query($conn, $sql);
}
经由过程本文的介绍,信赖你曾经控制了利用PHP实现高效数据导入导出的方法。在现实项目中,可能根据具体须要抉择合适的导入导出方法,以进步项目开辟效力。