How can an HTML table be converted to an xlsx format for export/download using PHP?
To convert an HTML table to an xlsx format for export/download using PHP, we can utilize a library like PHPExcel. This library allows us to read HTML tables and convert them into Excel files easily. We can parse the HTML table, create a new Excel file, and populate it with the table data before offering it for download.
<?php
require 'PHPExcel.php';
$html = '<table><tr><th>Name</th><th>Age</th></tr><tr><td>John Doe</td><td>30</td></tr><tr><td>Jane Smith</td><td>25</td></tr></table>';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->fromArray(array(array('Name', 'Age')), null, 'A1');
$highestRow = 1;
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('tr') as $row) {
$rowData = array();
foreach ($row->getElementsByTagName('td') as $cell) {
$rowData[] = $cell->nodeValue;
}
$highestRow++;
$objPHPExcel->getActiveSheet()->fromArray($rowData, null, 'A' . $highestRow);
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('html_table.xlsx');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="html_table.xlsx"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
?>
Keywords
Related Questions
- What role does the documentation play in understanding and implementing Amazon MWS API requests in PHP?
- What are the advantages of using str_replace over split() function in PHP for text manipulation?
- How can PHP and JavaScript be effectively combined to create a popup window with a form submission?