在PHP中进行数据格式化导出,可以使用以下几种常见方法:
$data = array(
array('Name', 'Age', 'Email'),
array('John Doe', 30, 'john.doe@example.com'),
array('Jane Smith', 25, 'jane.smith@example.com')
);
$fp = fopen('data.csv', 'w');
foreach ($data as $row) {
fputcsv($fp, $row);
}
fclose($fp);
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$data = array(
array('Name', 'Age', 'Email'),
array('John Doe', 30, 'john.doe@example.com'),
array('Jane Smith', 25, 'jane.smith@example.com')
);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
foreach ($data as $rowIndex => $row) {
foreach ($row as $colIndex => $value) {
$sheet->setCellValueByColumnAndRow($colIndex + 1, $rowIndex + 1, $value);
}
}
$writer = new Xlsx($spreadsheet);
$writer->save('data.xlsx');
$data = array(
array('Name' => 'John Doe', 'Age' => 30, 'Email' => 'john.doe@example.com'),
array('Name' => 'Jane Smith', 'Age' => 25, 'Email' => 'jane.smith@example.com')
);
$jsonData = json_encode($data);
file_put_contents('data.json', $jsonData);
通过以上方法,可以将数据以CSV、Excel或JSON格式导出到文件中,以满足不同的需求。