Reading XLSX in PHP without a library
# January 13, 2025,
I needed to read values from XLSX table. Existing PHP libraries seemed unnecessary heavy to me and I know that XLSX file basically just a ZIP archive so I thought that the data could be read directly from the XML files inside.
Here is the code. It reads data from the first sheet in the test.xlsx file and puts the (two dimensional) data into $rows
variable.
$file = 'test.xlsx'; $zip = new ZipArchive(); if (!$zip->open($filePath) die('Failed to open file'); $sharedStringsXML = $zip->getFromName("xl/sharedStrings.xml"); $sheetXML = $zip->getFromName("xl/worksheets/sheet1.xml"); $sharedStrings = []; if ($sharedStringsXML !== false) { $sharedStringsData = simplexml_load_string($sharedStringsXML); foreach ($sharedStringsData->si as $si) { $sharedStrings[] = (string)$si->t; } } $rowNumber = 0; $rows = []; $lastChar = false; if ($sheetXML !== false) { $sheetData = simplexml_load_string($sheetXML)->sheetData; foreach ($sheetData->row as $row) { $rowNumber++; $rowData = []; foreach ($row->c as $cell) { $value = null; $r = (string)$cell['r']; $char = substr($r, 0, 1); if($lastChar) { $c1 = ord($char) - 65; $c2 = ord($lastChar) - 65; $diff = $c1 - $c2; if($diff > 1) { for($i = 1; $i < $diff; $i++) { $rowData[] = ''; } } } $lastChar = $char; $type = (string)$cell['t']; if ($type === 's') { $value = $sharedStrings[(int)$cell->v]; } else { $value = (string)$cell->v; } $rowData[] = $value; } $rows[] = $rowData; } } $zip->close();