解决PHP身份证OCR识别返回乱码或字段缺失,核心在于统一编码为UTF-8并校验API响应结构。若出现乱码,需将GB2312/GBK转为UTF-8;若字段缺失,需检查JSON解析路径及必填项是否被过滤。

编码转换与iconv处理
国内主流OCR接口(如百度、腾讯)默认返回GBK或GB2312编码的中文数据,直接输出会导致乱码。需在接收响应后使用iconv函数进行转码。

先确认API文档中的字符集设置。通常返回的是GBK编码。使用iconv('GBK', 'UTF-8//IGNORE', $response)可将内容转换为UTF-8。//IGNORE参数用于忽略无法转换的非法字符,防止程序中断。若使用cURL请求,确保请求头中指定Accept-Encoding为gzip时,先解压再转码。
JSON解析与字段映射逻辑
字段缺失通常因JSON层级错误或关键字段未包含在返回包中导致。需构建健壮的解析逻辑,优先提取words_result节点。

<?php
// 配置信息
$appid = 'YOUR_APP_ID';
$api_key = 'YOUR_API_KEY';
$secret_key = 'YOUR_SECRET_KEY';
// 1. 获取Access Token
function getAccessToken($apiKey, $secretKey) {
$url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={$apiKey}&client_secret={$secretKey}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['access_token'])) {
return $data['access_token'];
}
throw new Exception('Failed to get access token: ' . $response);
}
// 2. 读取图片并Base64编码
$imagePath = 'id_card.jpg';
if (!file_exists($imagePath)) {
die("Image file not found.");
}
$imageContent = file_get_contents($imagePath);
$imageBase64 = base64_encode($imageContent);
// 3. 发起OCR请求
$token = getAccessToken($api_key, $secret_key);
$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={$token}";
$params = [
'id_card_side' => 'front', // front: 正面, back: 背面
'image' => $imageBase64
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
die("HTTP Error: {$httpCode}, Response: {$response}");
}
// 4. 解析结果
$result = json_decode($response, true);
if (!isset($result['words_result'])) {
die("No words result in response.");
}
$words = $result['words_result'];
// 5. 提取关键字段(注意:不同API返回的key可能略有差异,此处以百度为例)
$name = isset($words['姓名']['words']) ? $words['姓名']['words'] : '';
$number = isset($words['公民身份号码']['words']) ? $words['公民身份号码']['words'] : '';
$address = isset($words['住址']['words']) ? $words['住址']['words'] : '';
$sex = isset($words['性别']['words']) ? $words['性别']['words'] : '';
$birth = isset($words['出生']['words']) ? $words['出生']['words'] : '';
$ethnicity = isset($words['民族']['words']) ? $words['民族']['words'] : '';
// 6. 编码转换(如果API返回GBK)
// 假设API返回的是GBK编码,需转换为UTF-8
$name = iconv('GBK', 'UTF-8//IGNORE', $name);
$number = iconv('GBK', 'UTF-8//IGNORE', $number);
$address = iconv('GBK', 'UTF-8//IGNORE', $address);
$sex = iconv('GBK', 'UTF-8//IGNORE', $sex);
$birth = iconv('GBK', 'UTF-8//IGNORE', $birth);
$ethnicity = iconv('GBK', 'UTF-8//IGNORE', $ethnicity);
// 输出结果
echo "姓名: " . $name . "\n";
echo "号码: " . $number . "\n";
echo "地址: " . $address . "\n";
echo "性别: " . $sex . "\n";
echo "出生: " . $birth . "\n";
echo "民族: " . $ethnicity . "\n";
运行脚本前需替换appid、api_key和secret_key,并确保当前目录下存在id_card.jpg。成功执行后,终端将打印出转换后的UTF-8中文字符。若遇到乱码,检查iconv源编码是否为GBK;若字段缺失,检查words_result中对应键名是否与API文档一致,部分API可能返回name而非姓名。
OCR API返回的标准JSON结构通常包含log_id和words_result。身份证识别涉及姓名、号码、地址等多字段。需遍历words_result数组,通过key匹配具体字段值。若某字段为空,可能是图片清晰度不足或角度倾斜导致识别置信度低,此时应返回空字符串而非报错。
完整识别脚本与异常处理
以下代码演示了完整的调用流程:获取Token、发起请求、解码响应、提取身份证关键字段,并处理可能的编码问题。