Home >Web Front-end >CSS Tutorial >How to Efficiently Retrieve DOM Elements by Class Name Using PHP?
How to Retrieve DOM Elements by Class Name
Retrieving sub-elements with specific class names from DOM nodes can be achieved using various methods. Here are some approaches:
Using PHP DOM
PHP DOM provides a powerful way to manipulate HTML documents. To grab elements with a given class name, you can use Xpath selectors:
$dom = new DomDocument(); $dom->load($filePath); $finder = new DomXPath($dom); $classname = "my-class"; $nodes = $finder->query("//*[contains(@class, '$classname')]");
Using Zend_Dom_Query
This library offers a convenient interface for working with CSS selectors, making it easier to select elements:
$finder = new Zend_Dom_Query($html); $classname = 'my-class'; $nodes = $finder->query("*[class~=\"$classname\"]");
Using Xpath Version of *[@class~='my-class'] CSS Selector
After further investigation, an Xpath version of the CSS selector was discovered:
[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]
Utilizing this xpath in PHP:
$finder = new DomXPath($dom); $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 Using PHP?. For more information, please follow other related articles on the PHP Chinese website!