DOMDocument need to search for an element that has

2019-06-04 20:17发布

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?

2条回答
Evening l夕情丶
2楼-- · 2019-06-04 20:41

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.

查看更多
冷血范
3楼-- · 2019-06-04 20:43

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.

查看更多
登录 后发表回答