Home » Php » amazon web services – Textract not showing response in PHP

amazon web services – Textract not showing response in PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m attempting to use Amazon’s Textract API for parsing PDF files content & extracting emails, however it appears that you need to use the async method; I’ve done so but I’m unable to see/print data.

Here’s my code:

<?php

    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    //set environment values
    define('AWS_ACCESS_KEY_ID', '');
    define('AWS_SECRET_ACCESS_KEY', '');

    //require SDK
    require 'vendor/autoload.php';

    use Aws\Textract\TextractClient;

    function get_emails($file_path)
    {
        $client = new TextractClient([
            'region' => 'us-east-1',
            'version' => 'latest',
            'credentials' => [
                'key'    => AWS_ACCESS_KEY_ID,
                'secret' => AWS_SECRET_ACCESS_KEY
            ]
        ]);
        $file = fopen($file_path, "rb");
        $contents = fread($file, filesize($file_path));
        fclose($file);
        $options = [
            'Document' => [
                'Bytes' => $contents
            ],
            'FeatureTypes' => ['FORMS'],
        ];
        $promise = $client->analyzeDocumentAsync($options);
        $promise->then(
            // $onFulfilled
            function ($value) {
                echo 'The promise was fulfilled.';
                processResult($value);
            },
            // $onRejected
            function ($reason) {
                echo 'The promise was rejected.';
            }
        );
    }

    function processResult($result) {
        $blocks = $result['Blocks'];
        // Loop through all the blocks:
        foreach ($blocks as $key => $value) {
            if (isset($value['BlockType']) && $value['BlockType']) {
                $blockType = $value['BlockType'];
                if (isset($value['Text']) && $value['Text']) {
                    $text = $value['Text'];
                    if ($blockType == 'WORD') {
                        echo "Word: ". print_r($text, true) . "\n";
                    } else if ($blockType == 'LINE') {
                        echo "Line: ". print_r($text, true) . "\n";
                    }
                }
            }
        }
    }

    get_emails('1.pdf');

Whether I run this via browser or console, I’m getting no data?

How to&Answers: