The method is not supported by PHPs DOMDocument. It can be emulated by Xpath. Any CSS3 selector that does not return pseudo elements can be converted into an Xpath expression.
So to match a CSS class attribute you have to understand how it works. A CSS class is a token attribute. It contains several class names separated by whitespaces. In Xpath here is a method that can normalize the whitespaces to single spaces. If use that on a class attribute and add a space to the front and back any token matches the pattern {space}ClassOne{space}
. With several tokens you would end up with something like {space}ClassOne{space}ClassTwo{space}ClassThree{space}
. The important part is that does contain Class
but not {space}Class{space}
.
The CSS selector .className
can be converted into to the Xpath expression .//*[contains(concat(" ", normalize-space(@class), " "), " className ")]
. The first part normalizes the attribute so that it matches the token and not just the string that could be part of a token name.
In your case you can refine that to match div
elements:
.//div[contains(concat(" ", normalize-space(@class), " "), " localImage ")]
To use Xpath you need to create an DOMXpath instance for the document.
$document = new DOMDocument();
$document->loadHTML($html2);
$xpath = new DOMXpath($document);
$expression = './/div[contains(concat(" ", normalize-space(@class), " "), " localImage ")]';
foreach ($xpath->evaluate($expression) as $div) {
//...
}