What is the difference between creating a CSV file and an Excel file using PHP?
Creating a CSV file using PHP involves writing data in a comma-separated format, while creating an Excel file involves generating a file in a format that Excel can read, such as XLSX. To create a CSV file, you simply need to write data with commas separating each value. To create an Excel file, you may need to use a library like PHPExcel to generate the file in the correct format.
// Creating a CSV file
$csvData = "Name, Age, City\nJohn, 25, New York\nJane, 30, Los Angeles";
file_put_contents('data.csv', $csvData);
// Creating an Excel file using PHPExcel library
require 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Name')
->setCellValue('B1', 'Age')
->setCellValue('C1', 'City')
->setCellValue('A2', 'John')
->setCellValue('B2', 25)
->setCellValue('C2', 'New York')
->setCellValue('A3', 'Jane')
->setCellValue('B3', 30)
->setCellValue('C3', 'Los Angeles');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('data.xlsx');
Keywords
Related Questions
- How can namespaces be effectively used to streamline the inclusion of classes from different directories and eliminate the need for repetitive require_once statements in PHP?
- How can learning PHP help in creating a custom browser game script?
- Are there best practices for creating and maintaining sessions in PHP?