
PHP 8.0 起彻底移除了使用花括号(如 $str{0} 或 $arr{'key'})访问字符串和数组元素的旧语法,导致依赖该语法的旧 Excel 库(如 PHPExcel)报错“Array and string offset access syntax with curly braces is no longer supported”。本文提供兼容性修复与现代化替代方案。
php 8.0 起彻底移除了使用花括号(如 `$str{0}` 或 `$arr{'key'}`)访问字符串和数组元素的旧语法,导致依赖该语法的旧 excel 库(如 phpexcel)报错“array and string offset access syntax with curly braces is no longer supported”。本文提供兼容性修复与现代化替代方案。
该错误的根本原因在于:PHP 7.4 已废弃(deprecated)花括号下标语法(例如 $data['sheet']{5} 或 $str{0}),而 PHP 8.0+ 完全移除了该语法支持。许多老旧 CodeIgniter 第三方库(尤其是基于 PHPExcel 的 excel 库)大量使用了 $cell->value{0}、$string{1} 等写法,因此在 PHP 8.0 及更高版本中运行时直接触发致命错误。
✅ 正确做法不是降级 PHP(不推荐:牺牲安全、性能与新特性),而是升级库至现代标准:
✅ 推荐方案:迁移到 PhpSpreadsheet(PHPExcel 的官方继任者)
卸载旧库
删除application/libraries/excel.php及相关文件(如Classes/目录)。-
通过 Composer 安装 PhpSpreadsheet
在项目根目录执行:composer require phpoffice/phpspreadsheet
-
创建 CodeIgniter 兼容的封装库(
application/libraries/Excel.php)<?php defined('BASEPATH') OR exit('No direct script access allowed'); require_once APPPATH . 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader; class Excel { public $spreadsheet; public $writer; public function __construct() { $this->spreadsheet = new Spreadsheet(); $this->writer = new Xlsx($this->spreadsheet); } public function load($file_path) { $reader = new XlsxReader(); return $reader->load($file_path); } public function output($filename = 'export.xlsx') { header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $filename . '"'); header('Cache-Control: max-age=0'); $this->writer->save('php://output'); } } -
在控制器中调用
Build MCP servers and clients for PHP applications with the official PHP SDK下载使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
public function __construct() { parent::__construct(); $this->load->library('excel'); $this->load->model('Crud_model'); } public function export() { $sheet = $this->excel->spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'ID')->setCellValue('B1', 'Name'); // ... 填充数据 $this->excel->output('users.xlsx'); }
⚠️ 注意事项
- 不要尝试用
str_replace批量将{替换为[—— 花括号在正则、注释、类定义等场景中合法,盲目替换极易引入语法错误; - 若必须临时兼容旧库,请将 PHP 降至 7.4.x(仅限开发过渡,生产环境严禁);
- PhpSpreadsheet 默认支持
.xlsx,如需.xls(Excel 97–2003),需额外安装phpoffice/phpexcel的兼容层(不推荐),或改用Ods格式; - CodeIgniter 3 用户建议同步升级至 CI4 + Namespaced autoloading,以获得更优的 Composer 集成体验。
? 总结:该错误是 PHP 语言演进的必然结果。拥抱 PhpSpreadsheet 不仅解决兼容性问题,更能获得持续维护、安全更新、内存优化及新功能(如公式计算、图表、样式链式调用)。迁移成本可控,长期收益显著。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










