如何在PHP中读取xls数据?代码导入异常原因咨询
Hey there! Let's break down how to read XLS files in PHP and troubleshoot those frustrating exceptions you're encountering.
The most reliable tool for this job is PhpSpreadsheet—it's the actively maintained successor to the legacy PHPExcel library, so it supports modern PHP versions and fixes many old bugs.
Step 1: Install PhpSpreadsheet
Use Composer to add it to your project (this is the easiest way):
composer require phpoffice/phpspreadsheet
Step 2: Basic Reading Code
Here's a simple example to load an XLS file and iterate through its data:
<?php require 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\IOFactory; try { // Load the XLS file $spreadsheet = IOFactory::load('./path/to/your-file.xls'); $activeSheet = $spreadsheet->getActiveSheet(); // Loop through each row to extract data foreach ($activeSheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); // Include empty cells if needed $rowData = []; foreach ($cellIterator as $cell) { $rowData[] = $cell->getValue(); } // Do something with $rowData (e.g., save to database, print) print_r($rowData); echo PHP_EOL; } } catch (Exception $e) { echo "Error reading file: " . $e->getMessage(); }
If you can't use Composer (e.g., in an older environment), you can still use PHPExcel, but note that it's no longer updated—so PhpSpreadsheet is strongly recommended.
Let's go through the most frequent reasons your import might be failing:
Incorrect file path: Double-check that the path to your XLS file is correct. Using an absolute path (like
realpath('./your-file.xls')) avoids relative path issues. You can add a check likeif (!file_exists($filePath)) { throw new Exception("File not found!"); }to catch this early.Corrupted XLS file: Try opening the file in Microsoft Excel or LibreOffice—if it throws an error there, the file itself is damaged. Repair it in Excel (File > Open > Browse > select file > Open and Repair) before trying to read it with PHP.
Missing PHP extensions: PhpSpreadsheet requires several extensions to work, including
php_zip,php_xml,php_gd2(for handling images in spreadsheets), andphp-mbstring. Check yourphpinfo()output to confirm these are enabled—if not, enable them in yourphp.inifile or via your hosting control panel.File permission issues: The PHP process (usually run as your web server user, e.g.,
www-dataon Linux) might not have read access to the file. On Linux, set the file permissions to644withchmod 644 your-file.xls, and ensure the parent directory is accessible too.Confusing XLS with XLSX: XLS is the old binary Excel format, while XLSX is the newer XML-based format. If you're forcing the wrong reader (e.g., using
XlsReaderfor an XLSX file), you'll get an error. Let IOFactory auto-detect the format withIOFactory::load(), or explicitly specify the reader if needed:$reader = IOFactory::createReader('Xls'); // For .xls files $spreadsheet = $reader->load('./your-file.xls');Insufficient memory: Large XLS files can exceed PHP's default memory limit. Increase it temporarily at the top of your script with
ini_set('memory_limit', '256M');(adjust the value based on your file size—you might need 512M or more for very large files).
内容的提问来源于stack exchange,提问作者xRobot

