Getting a DOM element with a specific class name is a common task in web scraping and automation. PHP offers multiple ways to achieve this:
Using XPath
The following XPath query can be used to select elements based on their class name:
//*[contains(@class, 'CLASS_NAME')]
For example:
$dom = new DomDocument(); $dom->load($filePath); $finder = new DomXPath($dom); $classname = "my-class"; $nodes = $finder->query("//*[contains(@class, '$classname')]");
Using CSS Selector Syntax
Zend_Dom_Query, a PHP library, supports CSS selector syntax, allowing you to use the following CSS selector:
*[class~="CLASS_NAME"]
For example:
$finder = new Zend_Dom_Query($html); $classname = 'my-class'; $nodes = $finder->query("*[class~='$classname']");
Additional Notes:
The above is the detailed content of How Can I Get DOM Elements by Class Name in PHP?. For more information, please follow other related articles on the PHP Chinese website!