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> <p>The XPath query will correctly select the element with the "date" class and ignore the "foobar" element.</p> <p><strong>Incorrect Approaches:</strong></p> <ul> <li>//*[@class="foo"]: Doesn't match elements with multiple classes.</li> <li>//*[contains(@class, "foo")]: Matches elements with a class containing "foo" as a substring, even if it's part of a longer class name like "foobar".</li> </ul> </div>
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!