In PHP I'm using DOMDocument and I need to search for an element that has attribute class="something"
I'm new with DOMDocument (been using REGEX all my life so help me :P)
Ok, my question is, I've found a DOMElement using getElementById, now i want to look inside the children of this element and retrieve a node that has a particular class, class="something"
How do i do that?
Once you have a DOMNode
$n
for a document $d
whose children you want to filter by class you can do (this searches recursively):
$xp = new DOMXpath($d);
foreach ($xp->query('//*[contains(@class, \'classname\')]', $n) as $found) {
//do sth with $found
}
The point of contains
is to catch those nodes whose class attribute has more than one value, but it's a bit too coarse. See here for a better solution.
Use an XPath query:
$xpath = new DOMXPath($document);
// keep the quotes around the classname
$elementsThatHaveMyClass = $xpath->query('//*[@class="class here"]');
The expression means "from anywhere in the document, find any tag whose class
attribute is equal to class here
". You can read more on the XPath syntax here.