php - DOMDocument need to search for an element that has attribute class="something"
Get the solution ↓↓↓Solution:
Once you have aDOMNode
$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 ofcontains
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.
Answer
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 whoseclass
attribute is equal toclass here
". You can read more on the XPath syntax here.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.