Home > Article > Backend Development > Alibaba Cloud OCR and PHP development: a practical tutorial example
Alibaba Cloud OCR and PHP development: a practical tutorial example
composer require alibabacloud/sdk
After the installation is complete, we can create an OCR Client and set the AccessKeyId and AccessKeySecret:
<?php require_once __DIR__ . '/vendor/autoload.php'; use AlibabaCloudClientAlibabaCloud; use AlibabaCloudClientExceptionClientException; use AlibabaCloudClientExceptionServerException; use AlibabaCloudOcrOcr; // 设置AccessKeyId和AccessKeySecret AlibabaCloud::accessKeyClient('{AccessKeyId}', '{AccessKeySecret}') ->regionId('cn-hangzhou') ->name('default') ->timeout(20) ->connectTimeout(0) ->asGlobalClient(); // 创建OCR Client $client = new Ocr();
Next, we You can use OCR Client to call the OCR API. For example, the following sample code demonstrates how to use the OCR API to perform text recognition on a picture:
<?php try { $result = $client->v20191230()->recognizeBusinessCard() ->withImageUrl('https://example.com/image.jpg') ->request(); print_r($result->toArray()); } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; }
The above code implements text recognition on a business card picture and prints out the recognition results.
business_license.jpg
, from which we want to extract the company name, legal representative, registered capital and other information. <?php try { $result = $client->v20191230()->recognizeBusinessLicense() ->withImageUrl('https://example.com/business_license.jpg') ->request(); $info = $result->toArray()['data']['config']['tables'][0]['rows']; $companyName = $info[0]['row'][1]['text']; $legalPerson = $info[6]['row'][1]['text']; $registeredCapital = $info[8]['row'][1]['text']; echo '公司名称:' . $companyName . PHP_EOL; echo '法定代表人:' . $legalPerson . PHP_EOL; echo '注册资本:' . $registeredCapital . PHP_EOL; } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; }
The above code extracts the information from the business license image and prints it out by calling the recognizeBusinessLicense
interface.
The above is the detailed content of Alibaba Cloud OCR and PHP development: a practical tutorial example. For more information, please follow other related articles on the PHP Chinese website!