The deleteMatchingObjects() method in the AWS PHP SDK is used to delete objects from an S3 bucket based on a given prefix. However, you are correct that this method does not return the count of deleted objects directly.

If you need to get the count of deleted objects, you can use additional logic to track the number of objects deleted during the operation. Here's an example of how you can achieve this:

use Aws\S3\S3Client; use Aws\Exception\AwsException; // Instantiate the S3 client $s3Client = new S3Client([ 'region' => 'your-region', 'version' => 'latest', 'credentials' => [ 'key' => 'your-access-key', 'secret' => 'your-secret-key', ], ]); // Your bucket and prefix $bucket = 'your-bucket-name'; $prefix = 'your-prefix/'; // Initialize the counter $deletedCount = 0; // Use a paginator to handle large datasets (optional but recommended for large operations) $paginator = $s3Client->getPaginator('ListObjects', [ 'Bucket' => $bucket, 'Prefix' => $prefix, ]); // Iterate through objects and delete them foreach ($paginator as $result) { foreach ($result['Contents'] as $object) { try { $s3Client->deleteObject([ 'Bucket' => $bucket, 'Key' => $object['Key'], ]); $deletedCount++; } catch (AwsException $e) { // Handle errors if needed } } } // Print or use the deleted count echo "Deleted objects count: $deletedCount";

In this example, we use the ListObjects operation with a paginator to retrieve a list of objects with the specified prefix. Then, we iterate through the objects and delete each one using the deleteObject() method. The $deletedCount variable keeps track of the number of successfully deleted objects.

Please note that iterating through large datasets can take time, and you should consider using pagination to handle large operations efficiently. Additionally, consider adding appropriate error handling based on your application's requirements.

If you want to retrieve a count without actually deleting the objects, you can modify the logic accordingly, using a similar approach to iterate through the objects and increment the count without making any deletion calls.

Have questions or queries?
Get in Touch