利用 cURL 库发起 POST 类型的网络请求,将经过 Base64 编码处理的图像数据嵌入到 JSON 格式的 Body 中,同时附带 Access Token 凭证,以此访问百度的 AI OCR API 服务。

获取 Access Token 与准备环境
在正式调用接口之前,必须通过 AppID(AppID)和 Secret Key(Secret Key)向认证服务器申请 Access Token,这是完成身份鉴权的核心环节。需确认服务器环境中已安装 PHP cURL 扩展模块,并持有有效的 API 密钥信息。

Access Token 的有效周期一般为 30 天,推荐采用缓存机制以复用该令牌。OCR 服务提供多种识别模式,本示例选用通用高精度版。输入图像需转换为 Base64 字符串格式,务必剔除头部元数据(例如 data:image/jpeg;base64,),仅保留纯净的 Base64 数据。若图像体积过大,应实施压缩或分块策略,单次请求通常限制在几 MB 以内。
构建 cURL 请求并发送数据
开发 PHP 脚本,组装包含 access_token、image 参数以及 image_type=json 的请求负载,并将 Content-Type 头设置为 application/json。

<?php
// 配置信息
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
$ocrUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic';
// 1. 获取 Access Token
function getAccessToken($url, $key, $secret) {
$postUrl = $url . '?grant_type=client_credentials&client_id=' . $key . '&client_secret=' . $secret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response)->access_token;
}
// 2. 执行 OCR
function ocrImage($token, $imageUrl) {
// 读取图片并转为 Base64
$imageData = file_get_contents($imageUrl);
$base64Img = base64_encode($imageData);
// 构造请求参数
$params = [
'access_token' => $token,
'image' => $base64Img,
'image_type' => 'BASE64'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ocrUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// 主流程
$token = getAccessToken($accessTokenUrl, $apiKey, $secretKey);
if (!$token) {
die('Failed to get access token');
}
$result = ocrImage($token, './test.jpg');
if (isset($result['error_code'])) {
echo "Error: " . $result['error_msg'];
} else {
foreach ($result['words_result'] as $word) {
echo $word['words_string'] . "\n";
}
}
程序首先获取 Token,随后读取本地 test.jpg 文件,将其编码后发送至百度 OCR 接口。若请求成功,则逐行输出识别到的文本内容;若失败,则打印详细的错误日志。请将 YOUR_API_KEY 和 YOUR_SECRET_KEY 替换为真实值,并确保 test.jpg 文件存在且具备可读权限。
获取 URL 的 URL 为 https://aip.baidubce.com/oauth/2.0/token,用于获取 Token;而 https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic 则用于执行 OCR 识别任务。必须校验 HTTP 状态码及返回的 error_code,非零值即代表失败。针对中文乱码问题,确保源文件编码为 UTF-8,且输出时不进行强制编码转换。如遇网络超时,可适当调整 curl_setopt 配置中的 timeout 参数。
处理返回结果与异常排查
解析返回的 JSON 数据,从 words_result 数组中提取文字内容,并处理如 invalid token 或 image format error 等潜在错误码。
成功响应结构中包含 words_result 数组,每个元素均含有 words_string 字段。若 error_code 返回值为 110,表明 Access Token 无效或已过期;若为 17,则可能是图片格式不支持或尺寸超限。建议在代码中加入 try-catch 块或条件判断逻辑,对常见错误提供友好提示。对于多语言混合或特殊符号场景,高精度版通常表现良好,但仍建议人工复核关键数据。避免在循环中频繁创建新的 cURL 句柄,可通过复用连接来提升性能。