PHP Html Parser: Fetching Data from Remote Sites

Hello! In this paragraph, I will talk about a very simple way of getting data from a site with PHP. First of all, we should include the PHP Html Parser library.

Using Composer

$ composer require paquettg/php-html-parser

To download manually
https://github.com/paquettg/php-html-parser

With PHP Html Parser library, you can parse the data on the remote site using CSS selectors.

To use this library, it is necessary to have a little code knowledge of CSS selectors.

I want to show the sample uses of PHP Html Parser.

<?php

use PHPHtmlParser\Dom;

// Include library (Assuming you installed from Composer)
require __DIR__ . '/vendor/autoload.php';

$dom = new Dom;

// Load from URL
$dom->loadFromUrl('https://www.minetoria.com');

Let’s try on a real site: minetoria.com
This site has a list of data, a paging structure and content that we can get.

// A list from all <div class="card"> elements under the <section class="pb-4"> tag.
$listDom = $dom->find('section.pb-4 .card');

$list = [];

foreach ($listDom as $item) {
    $list[] = [
        // Find <a class="h5 text-light"> and get the text.
        'server_title' => $item->find('a.h5.text-light')->text,
         // Find <a class="h5 text-light"> and get the "href" attribute.
        'server_link' => $item->find('a.h5.text-light')->href,
    ];
}
0 Shares:
1 comment
Leave a Reply

Your email address will not be published. Required fields are marked *