This topic describes how to use the PHP SDK to call the optical character recognition (OCR) operation to detect text in common images and return the results in real time.

Preparations

Before calling operations, make the following preparations:
  1. Create an AccessKey ID and AccessKey secret of your Alibaba Cloud account. For more information, see Create an AccessKey.
  2. Install PHP dependencies. For more information, see Installation.

Submit synchronous OCR tasks

Description
Operation Feature Region Description
ImageSyncScanRequest Sends synchronous OCR requests to detect text in images.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • ap-southeast-5: Indonesia (Jakarta)
This operation detects text in images after you specify ocr in the scenes parameter.
Sample code
<? php

require_once 'aliyuncs/aliyun-oss-php-sdk/autoload.php';
include_once 'aliyuncs/aliyun-php-sdk-core/Config.php';

use Green\Request\V20180509 as Green;

// Use the AccessKey ID and AccessKey secret of your Alibaba Cloud account.
$iClientProfile = DefaultProfile::getProfile("cn-shanghai", "Your AccessKey ID", "Your AccessKey secret");
DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
$client = new DefaultAcsClient($iClientProfile);

$request = new Green\ImageSyncScanRequest();
$request->setMethod("POST");
$request->setAcceptFormat("JSON");

$task1 = array('dataId' =>  uniqid(),
    'url' => 'https://xxx.jpg'
);
// Create one task for each image to be moderated.
// If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
// Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
// The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
// The OCR expense equals the product of the number of images moderated and the moderation unit price.
$request->setContent(json_encode(array(
    "tasks" => array($task1),
    "scenes" => array("ocr")
    )));
try {
    $response = $client->getAcsResponse($request);
   # print_r($response);
    if(200 == $response->code){
        $taskResults = $response->data;
        foreach ($taskResults as $taskResult) {
            if (200 == $taskResult->code) {
                $sceneResults = $taskResult->results;
                print_r($sceneResults);
            }
        }
    }else{
        print_r("detect not success. code:" + $response->code);
    }
} catch (Exception $e) {
    print_r($e);
}