simple-html-domvsxml2
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.
The xml2 package is a binding to libxml2, making it easy to work with HTML and XML from R. The API is somewhat inspired by jQuery.
xml2 can be used to parse HTML documents using XPath selectors and is a successor to R's XML package with a few improvements:
- xml2 takes care of memory management for you. It will automatically free the memory used by an XML document as soon as the last reference to it goes away.
- xml2 has a very simple class hierarchy so don't need to think about exactly what type of object you have, xml2 will just do the right thing.
- More convenient handling of namespaces in Xpath expressions - see xml_ns() and xml_ns_strip() to get started.
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();
library("xml2")
x <- read_xml("<foo> <bar> text <baz/> </bar> </foo>")
x
xml_name(x)
xml_children(x)
xml_text(x)
xml_find_all(x, ".//baz")
h <- read_html("<html><p>Hi <b>!")
h
xml_name(h)