Retrieving DOM Elements by Classname
When navigating HTML documents using PHP DOM, accessing elements based on their class names can be crucial. This question addresses the most effective approach to obtain sub-elements within a DOM node that possess a specified class attribute.
Xpath Selector Approach:
An Xpath selector can efficiently locate elements matching a given class name. For example, to retrieve elements with a class of "my-class," use the following Xpath:
$finder = new DomXPath($dom); $classname = "my-class"; $nodes = $finder->query("//*[contains(@class, '$classname')]");
CSS Selector Approach:
If you intend to perform extensive DOM element selection with complex selectors, consider using Zend_Dom_Query. It supports CSS selector syntax, making it similar to the jQuery library.
$finder = new Zend_Dom_Query($html); $classname = 'my-class'; $nodes = $finder->query("*[class~=\"$classname\"]");
Update: Xpath Equivalent of *[@class~='my-class'] CSS Selector
For those curious about the inner workings of Zend_Dom_Query, the above CSS selector compiles to the following Xpath:
[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]
This Xpath expression ensures that the class attribute contains the specified classname, even if surrounded by whitespace.
The above is the detailed content of How Can I Efficiently Retrieve DOM Elements by Class Name Using PHP?. For more information, please follow other related articles on the PHP Chinese website!