Laravel 9应用导入XML遇SSL错误(error:0A000126)如何解决?
解决file_get_contents SSL意外EOF报错的方案
以下是针对error:0A000126:SSL routines::unexpected eof while reading报错的几种可行处理方式:
1. 临时禁用SSL验证(仅用于排查,生产环境禁止)
当容器内CA证书未正确配置时,可临时跳过SSL验证确认问题来源:
public function load($fileName) { $filePath = 'https://___.xml'; // 创建跳过SSL验证的上下文 $context = stream_context_create([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ] ]); $xmlString = file_get_contents($filePath, false, $context); $xmlObject = simplexml_load_string($xmlString); $json = json_encode($xmlObject); $phpArray = json_decode($json, true); dd($phpArray); }
2. 更新容器内的CA证书
Docker容器默认CA证书可能过期或缺失,需更新证书库:
- 直接在WSL2的Ubuntu容器内执行命令:
apt-get update && apt-get install -y ca-certificates && update-ca-certificates
- 或在项目Dockerfile中添加以下步骤,确保构建镜像时自动更新证书:
RUN apt-get update \ && apt-get install -y ca-certificates \ && update-ca-certificates \ && rm -rf /var/lib/apt/lists/*
3. 指定兼容的SSL协议版本
部分目标服务器仅支持旧版TLS协议,可强制指定协议版本解决握手问题:
public function load($fileName) { $filePath = 'https://___.xml'; $context = stream_context_create([ 'ssl' => [ 'verify_peer' => true, 'verify_peer_name' => true, 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, // 或STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT ] ]); $xmlString = file_get_contents($filePath, false, $context); $xmlObject = simplexml_load_string($xmlString); $json = json_encode($xmlObject); $phpArray = json_decode($json, true); dd($phpArray); }
4. 改用Guzzle替代file_get_contents
Laravel官方推荐使用Guzzle处理HTTP请求,其对SSL的支持更稳定:
- 若未安装Guzzle,先执行:
composer require guzzlehttp/guzzle
- 修改控制器代码:
use GuzzleHttp\Client; public function load($fileName) { $client = new Client(); $response = $client->get('https://___.xml'); $xmlString = $response->getBody()->getContents(); $xmlObject = simplexml_load_string($xmlString); $json = json_encode($xmlObject); $phpArray = json_decode($json, true); dd($phpArray); }
内容的提问来源于stack exchange,提问作者Arek TG
相关产品推荐
相关产品推荐

