本文目录导读:

我理解你想了解如何使用PHP调用OCR(光学字符识别)API进行文字识别,由于你提到的是“通用API”,我假设你可能指的是市面上常见的OCR服务,如百度AI、腾讯云、阿里云、或者开源的Tesseract等,下面我将以百度AI的OCR API为例,提供一个最常用的实现流程和代码示例,因为这是国内开发者使用最广泛的方式之一。
核心思路
使用PHP调用OCR API,本质上是:
- 将图片数据(或图片URL)发送到云端OCR服务的接口。
- 接收返回的JSON数据。
- 从中提取出识别的文字内容。
准备工作(以百度智能云为例)
-
注册并创建应用
- 访问 [百度智能云控制台](ai.baidu.com)。
- 登录后,在“人工智能” -> “文字识别”中,创建应用。
- 创建成功后,你会获得三个关键参数:AppID、API Key、Secret Key。
-
获取Access Token
-
百度OCR API使用Access Token进行鉴权,你需要用API Key和Secret Key去换取一个临时的Token(有效期通常30天)。
-
获取Token的API端点:
POST https://aip.baidubce.com/oauth/2.0/token -
参数:
grant_type:固定值client_credentialsclient_id:你的API Keyclient_secret:你的Secret Key
-
PHP代码示例(获取Token):
<?php function getAccessToken() { $apiKey = '你的API_Key'; // 替换为你的 $secretKey = '你的Secret_Key'; // 替换为你的 $url = 'https://aip.baidubce.com/oauth/2.0/token'; $postData = [ 'grant_type' => 'client_credentials', 'client_id' => $apiKey, 'client_secret' => $secretKey ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); return $result['access_token'] ?? null; }
$token = getAccessToken(); echo "获取到的Access Token: " . $token; ?>
-
调用文字识别API
百度OCR提供多种接口(通用文字识别、高精度、手写体等),这里以通用文字识别为例。
- API端点:
POST https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=你的Token - 请求方法:
POST - 数据格式:
application/x-www-form-urlencoded - 参数(二选一):
image:图片的Base64编码字符串(注意不能包含data:image/...头信息)。url:图片的HTTP/HTTPS网络地址。
识别本地图片文件
<?php
function ocrLocalImage($imagePath, $accessToken) {
$url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $accessToken;
// 1. 读取图片文件并转换为Base64
$imageData = file_get_contents($imagePath);
$base64Image = base64_encode($imageData);
// 2. 构造POST数据
$postData = [
'image' => $base64Image
];
// 3. 发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 正式环境建议设为true
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 使用示例
$token = getAccessToken(); // 使用上面定义的函数
$result = ocrLocalImage('./test.jpg', $token);
// 输出结果
if (!empty($result['words_result'])) {
foreach ($result['words_result'] as $item) {
echo "识别文字: " . $item['words'] . "\n";
}
} else {
echo "识别失败: " . json_encode($result);
}
?>
识别网络图片URL
<?php
function ocrUrlImage($imageUrl, $accessToken) {
$url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $accessToken;
$postData = [
'url' => $imageUrl
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 使用示例
$result = ocrUrlImage('https://example.com/my-image.jpg', $token);
// 处理结果...
?>
高精度或特殊类型识别
如果你需要识别准确率更高的文字(如手写体、生僻字),可以换用不同的接口。
- 通用文字识别(高精度版):
https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic - 手写体识别:
https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting - 身份证识别:
https://aip.baidubce.com/rest/2.0/ocr/v1/idcard
使用方式与上述相同,只需修改API端点的URL即可。
处理返回结果
百度OCR返回的JSON格式大致如下:
{
"log_id": 123456789,
"words_result_num": 2,
"words_result": [
{"words": "你好"},
{"words": "世界"}
]
}
你可以从中提取字符串:
$textList = [];
foreach ($result['words_result'] as $item) {
$textList[] = $item['words'];
}
$fullText = implode("\n", $textList);
echo $fullText;
常见问题与注意事项
- cURL扩展:确保你的PHP环境已安装并启用了
curl扩展。 - 图片大小限制:百度OCR对图片大小有限制(通常Base64后不超过10MB),如果图片过大,可以先压缩再上传。
- Token有效期:获取的Access Token有有效期(百度是30天),建议缓存起来(如存入文件或数据库),过期再重新获取,避免反复请求Token接口。
- 错误处理:
- 检查返回结果中是否有
error_code字段,例如error_code: 110表示Access Token无效;error_code: 216100表示图片尺寸或格式问题。 - 常见错误码及解决方法:[百度OCR错误码文档](https://ai.baidu.com/ai-doc/OCR/Uk3bqkzrk)
- 检查返回结果中是否有
- PHP版本:建议使用PHP 7.0+,以上代码兼容。
其他OCR服务替代方案
如果你用的是其他服务,原理类似:
| 服务商 | API文档地址 | 主要鉴权方式 |
|---|---|---|
| 腾讯云 | [OCR文字识别](https://cloud.tencent.com/document/product/866) | SecretId + SecretKey |
| 阿里云 | [文字识别](https://help.aliyun.com/product/56937.html) | AccessKey |
| 开源Tesseract | 需要编译安装tesseract-ocr和PHP扩展php-tesseract |
无(本地部署) |
建议
如果你刚开始尝试,推荐先使用百度AI的免费额度(新用户有一定量免费调用次数),按照上述代码,你只需要替换API_Key和Secret_Key即可快速测试。
如果这只是你开始构建AI应用的第一步,后续你可能会遇到图片预处理(如降噪、纠正倾斜)或特殊场景(如发票、表格)的需求,遇到具体问题时,欢迎补充说明,我可以提供更针对性的代码或建议。