Getting DOM elements by classname

Viewed 220289

I'm using PHP DOM and I'm trying to get an element within a DOM node that have a given class name. What's the best way to get that sub-element?

Update: I ended up using Mechanize for PHP which was much easier to work with.

7 Answers

I prefer using Symfony for this. Their libraries are pretty nice.

Use the The DomCrawler Component

Example:

$browser = new HttpBrowser(HttpClient::create());
$crawler = $browser->request('GET', 'example.com');
$class = $crawler->filter('.class')->first();

PHP's native DOM handling is so absurdly bad, do yourself a favour and use this or any other modern HTML parsing package which can handle this within in few lines:

Install paquettg/php-html-parser with

composer require paquettg/php-html-parser

Then create a .php file in the same folder with this content

<?php

// load dependencies via Composer
require __DIR__ . '/vendor/autoload.php';

use PHPHtmlParser\Dom;

$dom = new Dom;
$dom->loadFromUrl("https://example.com");
$links = $dom->find('.classname a');

foreach ($links as $link) {
    echo $link->getAttribute('href');
}

P.S. You'll find information on how to install Composer on Composer's homepage.

Related