PHP code example of dantepiazza / apify

1. Go to this page and download the library: Download dantepiazza/apify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dantepiazza / apify example snippets


use DantePiazza\Apify\ApifyClient;

$client = new ApifyClient(token: 'apify_api_xxx');

$posts = $client->fetchInstagramPosts(
    accounts:     ['nasa', 'spacex'],
    resultsLimit: 50,
);

use DantePiazza\Apify\Cache\FileCache;

$client = new ApifyClient(
    token: 'apify_api_xxx',
    cache: new FileCache(
        directory: '/var/cache/apify',
        ttl: 3600,          // seconds; null = never expires (default)
    ),
);

$client = new ApifyClient(
    token:        'apify_api_xxx',
    cacheEnabled: false,
);

$posts = $client->withoutCache()->fetchInstagramPosts(['nasa']);

$client->flushCache();

use DantePiazza\Apify\Contracts\CacheInterface;

class RedisCache implements CacheInterface
{
    public function get(string $key): ?array { /* ... */ }
    public function put(string $key, array $data): void { /* ... */ }
    public function forget(string $key): void { /* ... */ }
    public function flush(): void { /* ... */ }
}

$client = new ApifyClient(
    token: 'apify_api_xxx',
    cache: new RedisCache($redis),
);

use DantePiazza\Apify\Contracts\NormalizerInterface;

class InstagramNormalizer implements NormalizerInterface
{
    public function normalize(array $item): ?array
    {
        // Return null to discard the item
        if (empty($item['timestamp'])) {
            return null;
        }

        return [
            'id'           => (string) ($item['id'] ?? $item['shortCode'] ?? uniqid()),
            'account'      => $item['ownerUsername'] ?? '',
            'caption'      => $item['caption'] ?? '',
            'image_url'    => $item['displayUrl'] ?? '',
            'post_url'     => $item['url'] ?? '',
            'published_at' => (new DateTimeImmutable($item['timestamp']))->format(DateTimeInterface::ATOM),
            'likes'        => $item['likesCount'] ?? 0,
            'comments'     => $item['commentsCount'] ?? 0,
        ];
    }
}

$client = new ApifyClient(
    token:      'apify_api_xxx',
    normalizer: new InstagramNormalizer(),
);

new ApifyClient(
    token:        string,               // mpts (×5s = ~5 min)
    httpTimeout:  int    = 30,          // Guzzle HTTP timeout in seconds
    cache:        ?CacheInterface = null,   // null → uses FileCache by default
    cacheEnabled: bool   = true,        // set false to disable cache entirely
    normalizer:   ?NormalizerInterface = null,  // null → PassthroughNormalizer
    verifySsl:    bool   = true,        // set false for local dev if needed
    verbose:      bool   = false,       // echo progress to stdout
);