search
HomeBackend DevelopmentPHP TutorialPHP practice: crawling Bilibili barrage data

PHP practice: crawling Bilibili barrage data

Jun 13, 2023 pm 07:08 PM
phpreptileBarrage

Bilibili is a barrage video website popular in China. It is also a treasure trove, containing all kinds of data. Among them, barrage data is a very valuable resource, so many data analysts and researchers hope to obtain this data. In this article, I will introduce the use of PHP language to crawl Bilibili barrage data.

  1. Preparation

Before starting to crawl the barrage data, we need to install a PHP crawler framework Symphony 2. It can be installed through the following command:

$ curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
$ chmod a+x /usr/local/bin/symfony

After that, we need to use Composer to install GuzzleHttp and PHP-DI dependent libraries:

$ composer require guzzlehttp/guzzle php-di/php-di

Next, we need to go to the Bilibili website to find the number of the corresponding video. It can be obtained through the browser F12 developer tools.

  1. Crawling barrage data

After obtaining the number of the Bilibili video, we can use GuzzleHttp to send a GET request to obtain the data, thereby obtaining the barrage list in the video information. The following is the code to obtain data:

$client = new GuzzleHttpClient();
$res = $client->request('GET', "https://api.bilibili.com/x/v1/dm/list.so?oid={$oid}");
$xml = simplexml_load_string($res->getBody(), 'SimpleXMLElement', LIBXML_NOCDATA);

After successfully obtaining the barrage list information, we encapsulate it into an array:

$items = [];

foreach ($xml->d->p as $p) {
    list($time, $type, $size, $color, $time) = explode(",", $p['p']);
    $content = (string) $p;
    $items[] = [
        'time' => (float) $time,
        'content' => $content
    ];
}

After we successfully obtain the barrage data, we It can be saved to the database for subsequent analysis and use:

$builder = $this->db->createQueryBuilder();
foreach ($items as $item) {
    $builder->insert('danmaku')
            ->values([
                '`time`' => ':time',
                '`content`' => ':content'
            ])
            ->setParameters([
                ':time' => $item['time'],
                ':content' => $item['content']
            ])
            ->execute();
}
  1. Analyzing barrage data

Next, we can start to analyze the obtained barrage Data are analyzed and presented. We can use PHP with Highcharts, a data visualization tool, to build a chart of the number of barrages. The following is the display data and code implementation:

$builder = $this->db->createQueryBuilder();

$data = $builder->select('COUNT(*) as cnt, FLOOR(`time`) as time')
                ->from('danmaku')
                ->groupBy('floor(`time`)')
                ->execute()
                ->fetchAll(PDO::FETCH_ASSOC);

echo $twig->render('danmaku.html.twig', [
    'data' => $data
]);
Highcharts.chart('container', {
    chart: {
        type: 'spline'
    },
    title: {
        text: '弹幕数量'
    },
    xAxis: {
        title: {
            text: '时间'
        }
    },
    yAxis: {
        title: {
            text: '数量'
        }
    },
    credits: {
        enabled: false
    },
    series: [{
        name: '弹幕数量',
        data: {{ data | json_encode }}
    }]
});
  1. Conclusion

Through this article, we have successfully used the PHP crawler framework Symphony 2 to crawl Bilibili barrage data function, analyzed the obtained data, and generated a chart of the number of barrages. In this process, we learned how to use PHP to send a GET request to obtain Bilibili video barrage data, and how to use Highcharts to display the data.

The above is the detailed content of PHP practice: crawling Bilibili barrage data. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools