simple-html-domvshtmlparser2
Simple HTML DOM Parser is a lightweight PHP library for parsing and manipulating HTML documents using a jQuery-like syntax. It is one of the most widely used HTML parsers in the PHP ecosystem, known for its simplicity and low learning curve.
Key features include:
- jQuery-like selectors Find elements using CSS selectors similar to jQuery: find('#id'), find('.class'), find('div > p'), etc.
- Easy element access Access element attributes, inner text, and inner HTML with simple property access: $element->plaintext, $element->href, $element->innertext.
- DOM manipulation Modify element attributes, text content, and HTML. Add or remove elements from the document tree.
- File and string parsing Parse HTML from strings, local files, or URLs directly.
- Nested element traversal Navigate parent, child, and sibling elements with built-in traversal methods.
- Memory-friendly Designed to handle large HTML documents efficiently with explicit memory cleanup.
Simple HTML DOM is best suited for quick scraping tasks and small projects where simplicity is more important than performance. For large-scale or performance-critical applications, consider using PHP's built-in DOMDocument or Symfony's DomCrawler which offer better performance and standards compliance.
htmlparser2 is a Node.js library for parsing HTML and XML documents. It works by building a tree of elements, similar to the Document Object Model (DOM) in web browsers. This allows you to easily traverse and manipulate the structure of the document.
htmlparser2 is a low-level html tree parser but it can still be useful in web scraping as it's a powerful tool for HTML restructuring and serialization.
Highlights
Example Use
<?php
require 'vendor/autoload.php';
use simplehtmldom\HtmlWeb;
use simplehtmldom\HtmlDocument;
// Parse HTML from a URL
$web = new HtmlWeb();
$html = $web->load('https://example.com');
// Or parse from a string
$html = new HtmlDocument('<div><p class="intro">Hello World</p></div>');
// Find elements using CSS-like selectors
$title = $html->find('title', 0)->plaintext;
echo "Title: $title\n";
// Find all products
foreach ($html->find('.product') as $product) {
$name = $product->find('.name', 0)->plaintext;
$price = $product->find('.price', 0)->plaintext;
$link = $product->find('a', 0)->href;
echo "$name: $price ($link)\n";
}
// Modify elements
$html->find('h1', 0)->innertext = 'Modified Title';
// Clean up memory when done
$html->clear();
const htmlparser = require("htmlparser2");
const parser = new htmlparser.Parser({
onopentag: (name, attribs) => {
console.log(`Opening tag: ${name}`);
},
ontext: (text) => {
console.log(`Text: ${text}`);
},
onclosetag: (name) => {
console.log(`Closing tag: ${name}`);
}
}, {decodeEntities: true});
const html = "<p>Hello, <b>world</b>!</p>";
parser.write(html);
parser.end();