Skip to content

Instantly share code, notes, and snippets.

@khoa-le
Created February 9, 2023 07:25
Show Gist options
  • Save khoa-le/73e18cf9638c525b24d6941a14b8aa5f to your computer and use it in GitHub Desktop.
Save khoa-le/73e18cf9638c525b24d6941a14b8aa5f to your computer and use it in GitHub Desktop.
Open AI Create Lamba services
Sure, here's an outline of the steps you can follow to develop an AWS Lambda function using PHP that reads data from an Excel file and saves it to Amazon DynamoDB:
Create a new Lambda function: Log in to the AWS Management Console, navigate to the Lambda service, and create a new function. Choose the "Author from scratch" option, and select PHP as the runtime.
Add an Amazon S3 trigger: In the designer section of the Lambda function, you can add an S3 trigger to trigger your function every time a new Excel file is uploaded to an S3 bucket.
Read the data from the Excel file: You can use a PHP library such as PHPExcel to read the data from the Excel file. You can access the uploaded file using the S3 bucket and key passed in the event data to the function.
Save the data to DynamoDB: To save the data to DynamoDB, you can use the AWS SDK for PHP to interact with the DynamoDB API. You can create a new DynamoDB table or use an existing one to save the data.
Test the function: After writing and deploying the code, you can test the function by uploading an Excel file to the S3 bucket and verifying that the data has been successfully saved to DynamoDB.
```php
use Aws\DynamoDb\DynamoDbClient;
use PHPExcel;
function lambda_handler($event, $context) {
// Read the data from the Excel file
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
$result = $s3->getObject([
'Bucket' => $event['Records'][0]['s3']['bucket']['name'],
'Key' => $event['Records'][0]['s3']['object']['key']
]);
$excel = PHPExcel_IOFactory::load($result['Body']);
$sheet = $excel->getActiveSheet();
$data = $sheet->toArray();
// Save the data to DynamoDB
$dynamodb = new DynamoDbClient([
'version' => 'latest',
'region' => 'us-east-1'
]);
foreach ($data as $row) {
$dynamodb->putItem([
'TableName' => 'table_name',
'Item' => [
'column_1' => [
'S' => $row[0]
],
'column_2' => [
'S' => $row[1]
],
// ...
]
]);
}
return 'Data saved to DynamoDB.';
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment