Retrieving DOM Elements Based on Class Name
In PHP DOM, extracting elements with specific class names is essential. This question presents a challenge faced by developers: finding the optimal method to isolate such elements within a DOM node.
To address this issue, several approaches are presented:
$dom = new DomDocument(); $dom->load($filePath); $finder = new DomXPath($dom); $classname = "my-class"; $nodes = $finder->query("//*[contains(@class, '$classname')]");
$finder = new Zend_Dom_Query($html); $classname = 'my-class'; $nodes = $finder->query("*[class~=\"$classname\"]");
Additionally, for scenarios involving XPath selectors with class name criteria, a more refined version is available:
$classname = "my-class"; $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
The above is the detailed content of How to Efficiently Retrieve DOM Elements by Class Name in PHP?. For more information, please follow other related articles on the PHP Chinese website!