Home >Backend Development >PHP Tutorial >How Can I Efficiently Select DOM Elements by Class Name Using PHP?
When working with PHP DOM, obtaining specific elements within a node based on their class is crucial. Let's explore the best approaches to achieve this:
$dom = new DomDocument();<br>$dom->load($filePath);<br>$finder = new DomXPath($dom);<br>$classname = "my-class";<br>$nodes = $finder->query("//*[contains(@class, '$classname')]");<br>
This approach uses XPath to select all elements with the specified class attribute.
If you prefer CSS selector syntax, Zend_Dom_Query offers a convenient solution:
$finder = new Zend_Dom_Query($html);<br>$classname = 'my-class';<br>$nodes = $finder->query("*[class~='$classname']");<br>
Update: XPath Version of *[@class~='my-class'] CSS Selector
Parsing the CSS selector using Zend_Dom_Query reveals an equivalent XPath expression:
$nodes = $finder->query("[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");<br>
By utilizing this XPath directly, you can query for elements containing the specified class without using Zend_Dom_Query.
When selecting elements by class, it's worth noting that if the element type is known, you can replace the * with the corresponding tag name, narrowing the search and improving efficiency.
The above is the detailed content of How Can I Efficiently Select DOM Elements by Class Name Using PHP?. For more information, please follow other related articles on the PHP Chinese website!