Home >Backend Development >PHP Tutorial >How to Select a CSS Class Using XPath?
How to Select a CSS Class with XPath
Issue:
You want to select a specific class called ".date" in an HTML document using XPath, but your attempts have been unsuccessful.
Code:
@$doc = new DOMDocument(); @$doc->loadHTML($html); $xml = simplexml_import_dom($doc); //Simplify XPath $images = $xml->xpath('//[@class="date"]');
Solution:
Unlike CSS, XPath does not natively support class selectors. However, there is a workaround:
Correct XPath Syntax:
//*[contains(concat(" ", normalize-space(@class), " "), " foo ")]
This expression matches any element whose class attribute contains the substring "foo".
Explanation:
Example:
<div>
The XPath query will correctly select the element with the "date" class and ignore the "foobar" element.
Incorrect Approaches:
The above is the detailed content of How to Select a CSS Class Using XPath?. For more information, please follow other related articles on the PHP Chinese website!