DOMDocument need to search for an element that has attribute class=“something”

旧时模样 提交于 2019-12-23 04:12:38

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3443701/domdocument-need-to-search-for-an-element-that-has-attribute-class-something

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!