PHP code example of haianibrahim / tiktok-scraper-laravel

1. Go to this page and download the library: Download haianibrahim/tiktok-scraper-laravel 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/ */

    

haianibrahim / tiktok-scraper-laravel example snippets


return [
    // HTTP Client Configuration
    'http_client' => [
        'timeout' => env('TIKTOK_SCRAPER_TIMEOUT', 30),
        'connect_timeout' => env('TIKTOK_SCRAPER_CONNECT_TIMEOUT', 10),
        'user_agent' => env('TIKTOK_SCRAPER_USER_AGENT', 'Mozilla/5.0...'),
        'headers' => [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language' => 'en-US,en;q=0.5',
            'Accept-Encoding' => 'gzip, deflate',
            'Connection' => 'keep-alive',
        ],
    ],

    // Caching Configuration
    'cache' => [
        'enabled' => env('TIKTOK_SCRAPER_CACHE_ENABLED', true),
        'store' => env('TIKTOK_SCRAPER_CACHE_STORE', null),
        'ttl' => env('TIKTOK_SCRAPER_CACHE_TTL', 3600),
        'prefix' => env('TIKTOK_SCRAPER_CACHE_PREFIX', 'tiktok_scraper'),
    ],

    // Rate Limiting Configuration
    'rate_limiting' => [
        'enabled' => env('TIKTOK_SCRAPER_RATE_LIMIT_ENABLED', true),
        'max_attempts' => env('TIKTOK_SCRAPER_RATE_LIMIT_MAX_ATTEMPTS', 60),
        'decay_minutes' => env('TIKTOK_SCRAPER_RATE_LIMIT_DECAY_MINUTES', 1),
    ],
];

use Hki98\LaravelTikTokScraper\Facades\TikTokScraper;

// Scrape a single video
$videoDetails = TikTokScraper::scrape('https://www.tiktok.com/@username/video/1234567890');

echo $videoDetails->description;
echo $videoDetails->username;
echo $videoDetails->views;

// Scrape a photo (slideshow) post - same method, same VideoDetails object
$photoPost = TikTokScraper::scrape('https://www.tiktok.com/@username/photo/1234567890');

echo $photoPost->userNickname;
echo $photoPost->likes;

// Scrape a user profile (accepts a bare username, @username, or profile URL)
$user = TikTokScraper::scrapeUser('scout2015');

echo $user->nickname;
echo $user->getFormattedFollowers(); // e.g. "9M"
echo $user->verified ? 'Verified' : 'Not verified';

// Scrape multiple videos
$videos = TikTokScraper::scrapeMultiple([
    'https://www.tiktok.com/@user1/video/1234567890',
    'https://www.tiktok.com/@user2/video/0987654321',
]);

// Validate input before scraping
if (TikTokScraper::isValidTikTokUrl($url)) {
    $videoDetails = TikTokScraper::scrape($url);
}

if (TikTokScraper::isValidUserInput($username)) {
    $user = TikTokScraper::scrapeUser($username);
}

// Cache management
TikTokScraper::clearCache();
TikTokScraper::clearUrlCache($url);

use Hki98\LaravelTikTokScraper\Contracts\TikTokScraperInterface;

class VideoController extends Controller
{
    public function __construct(
        private readonly TikTokScraperInterface $scraper
    ) {}

    public function scrape(Request $request)
    {
        $url = $request->input('url');
        
        try {
            $videoDetails = $this->scraper->scrape($url);
            return response()->json($videoDetails->toArray());
        } catch (TikTokScraperException $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}

$videoDetails = TikTokScraper::scrape($url);

// Basic information
echo $videoDetails->videoId;
echo $videoDetails->description;
echo $videoDetails->canonicalUrl;
echo $videoDetails->thumbnail;

// User information
echo $videoDetails->username;
echo $videoDetails->userNickname;
echo $videoDetails->userId;
echo $videoDetails->getUserProfileUrl(); // https://www.tiktok.com/@username

// Statistics
echo $videoDetails->views;
echo $videoDetails->likes;
echo $videoDetails->comments;
echo $videoDetails->shares;
echo $videoDetails->favorites;

// Calculated metrics & helpers
echo $videoDetails->getEngagementRate();   // Percentage of views
echo $videoDetails->getTotalEngagement();  // likes + comments + shares + favorites
echo $videoDetails->getFormattedViews();   // e.g. "1.5M"
echo $videoDetails->getFormattedLikes();   // e.g. "35.1K"
echo $videoDetails->getEmbedUrl();

// Convert to array/JSON
$array = $videoDetails->toArray();
$json = $videoDetails->toJson();

$user = TikTokScraper::scrapeUser('scout2015');

// Identity
echo $user->userId;
echo $user->secUid;
echo $user->username;
echo $user->nickname;
echo $user->signature;
echo $user->region;

// Avatars
echo $user->avatarThumb;
echo $user->avatarMedium;
echo $user->avatarLarger;

// Flags
echo $user->verified ? 'verified' : 'not verified';
echo $user->privateAccount ? 'private' : 'public';

// Counts
echo $user->followerCount;
echo $user->followingCount;
echo $user->heartCount;
echo $user->videoCount;

// Helpers
echo $user->getProfileUrl();        // https://www.tiktok.com/@username
echo $user->getFormattedFollowers(); // e.g. "9M"
echo $user->getFormattedHearts();    // e.g. "108.2M"

// Convert to array/JSON
$array = $user->toArray();
$json = $user->toJson();

use Hki98\LaravelTikTokScraper\Events\VideoScraped;

// Listen for successful scrapes
Event::listen(VideoScraped::class, function (VideoScraped $event) {
    Log::info('Video scraped successfully', [
        'url' => $event->url,
        'video_id' => $event->videoDetails->videoId,
        'username' => $event->videoDetails->username,
    ]);
});

use Hki98\LaravelTikTokScraper\Events\UserScraped;

Event::listen(UserScraped::class, function (UserScraped $event) {
    Log::info('User scraped successfully', [
        'input' => $event->input,
        'user_id' => $event->userInfo->userId,
        'username' => $event->userInfo->username,
    ]);
});

use Hki98\LaravelTikTokScraper\Events\ScrapingFailed;

Event::listen(ScrapingFailed::class, function (ScrapingFailed $event) {
    Log::error('Scraping failed', [
        'url' => $event->url,
        'error' => $event->exception->getMessage(),
    ]);
});

use Hki98\LaravelTikTokScraper\Events\RateLimitHit;

Event::listen(RateLimitHit::class, function (RateLimitHit $event) {
    Log::warning('Rate limit hit', [
        'url' => $event->url,
    ]);
});

use Hki98\LaravelTikTokScraper\Exceptions\{
    TikTokScraperException,
    InvalidUrlException,
    HttpRequestException,
    EmptyResponseException,
    ParseException,
    RateLimitException
};

try {
    $videoDetails = TikTokScraper::scrape($url);
} catch (InvalidUrlException $e) {
    // Handle invalid URL or user input
} catch (RateLimitException $e) {
    // Handle rate limiting
} catch (HttpRequestException $e) {
    // Handle HTTP errors
} catch (EmptyResponseException $e) {
    // Handle empty responses
} catch (ParseException $e) {
    // Handle parsing errors
} catch (TikTokScraperException $e) {
    // Handle general scraper errors
}
bash
php artisan vendor:publish --provider="Hki98\LaravelTikTokScraper\TikTokScraperServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="Hki98\LaravelTikTokScraper\TikTokScraperServiceProvider" --tag="migrations"
php artisan migrate
bash
php artisan tiktok-scraper:test https://www.tiktok.com/@username/video/1234567890
bash
# From file with JSON output
php artisan tiktok-scraper:bulk urls.txt --output=results.json

# From file with CSV output
php artisan tiktok-scraper:bulk urls.txt --output=results.csv --format=csv
bash
# Show stats
php artisan tiktok-scraper:stats

# Clear stats
php artisan tiktok-scraper:stats --clear
bash
# Clear all cache
php artisan tiktok-scraper:clear-cache

# Clear specific cache
php artisan tiktok-scraper:clear-cache --url="https://www.tiktok.com/@username/video/1234567890"

# Clear with confirmation
php artisan tiktok-scraper:clear-cache --force