
PHP 8.0 起彻底移除了使用花括号({})访问数组元素或字符串字符的语法(如 $str{0} 或 $arr{'key'}),导致旧版 Excel 库(如 PHPExcel)在高版本 PHP 中报错“Array and string offset access syntax with curly braces is no longer supported”。本文提供兼容性修复与现代化替代方案。
php 8.0 起彻底移除了使用花括号(`{}`)访问数组元素或字符串字符的语法(如 `$str{0}` 或 `$arr{'key'}`),导致旧版 excel 库(如 phpexcel)在高版本 php 中报错“array and string offset access syntax with curly braces is no longer supported”。本文提供兼容性修复与现代化替代方案。
该错误并非 CodeIgniter 或项目配置问题,而是第三方 Excel 库(极大概率是 PHPExcel)与 PHP 8.0+ 不兼容所致。PHP 从 7.4 开始已废弃 {} 下标语法(触发 E_DEPRECATED),而 PHP 8.0 正式将其移除——所有形如 $data{'name'} 或 $str{2} 的写法均会抛出致命错误 ParseError。
✅ 推荐解决方案:迁移到 PhpSpreadsheet(官方继任者)
PHPExcel 已于 2017 年停止维护,其官方团队开发了完全向后兼容、且全面适配 PHP 7.2–8.3 的现代替代库:PhpSpreadsheet。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
步骤 1:卸载旧库,安装 PhpSpreadsheet
# 若通过 Composer 管理(强烈推荐) composer remove phpoffice/phpexcel composer require phpoffice/phpspreadsheet
步骤 2:更新 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;
class Excel {
public function __construct() {
log_message('info', 'PhpSpreadsheet library loaded.');
}
public function create($filename = 'export.xlsx') {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
}
}
步骤 3:控制器中调用(保持原有风格)
public function __construct() {
parent::__construct();
$this->load->library('excel'); // 加载新封装的 Excel 库
$this->load->model('Crud_model');
}
public function export() {
$this->excel->create('report.xlsx');
}
⚠️ 注意事项
- 切勿降级 PHP 版本:为兼容旧库而使用 PHP 7.4 或更低版本存在严重安全风险,且违背现代开发规范;
-
手动修改旧库风险极高:PHPExcel 源码中
{}用法超百处(如PHPExcel_CachedObjectStorage_Memory.php),全局替换为[]仅是表层修复,还涉及__get()、__set()、反射及内部结构变更,极易引发隐性崩溃; -
CodeIgniter 3 用户注意:确保
vendor/目录可被 Web 服务器读取(避免.htaccess或 Nginx 配置误拦截);CI3 默认不启用 Composer 自动加载,需在application/config/config.php中确认composer_autoload设置为TRUE或路径正确。
✅ 总结
根本解决之道不是绕过语法限制,而是拥抱生态演进:用 PhpSpreadsheet 替代 PHPExcel,不仅彻底规避 {} 语法错误,更获得性能提升、安全更新、ActiveRecord 式链式 API 及完整文档支持。迁移成本可控(核心读写逻辑几乎无需重写),是面向未来最稳健的技术决策。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










