Find immediate children using PHP Simple DOM parser
I would like to be able to make an equivalent
$html->find("#foo>ul")
But the PHP Simple DOM library does not recognize the “immediate descendant” selector >
and therefore finds all <ul>
elements under #foo
, including those deeper nested in dom.
What would you recommend as the best way to capture immediate descendants of a particular type?
You can use DomElementFilter to select the desired node type under a certain Dom branch. This is described here:
PHP DOM: How to get children by tag name in an elegant way?
:
foreach ($parent->childNodes as $node)
if ($node->nodeName == "tagname1")
...
, , : " PHP Simple DOM parser" ...
... PHP Simple DOM:
//if there is only one div containing your searched tag
foreach ($html->find('div.with-given-class')[0]->children() as $div_with_given_class) {
if ($div_with_given_class->tag == 'tag-you-are-searching-for') {
$output [] = $div_with_given_class->plaintext; //or whatever you want
}
}
//if there are more divs with a given class (better solution)
$all_divs_with_given_class =
$html->find('div.with-given-class');
foreach ($all_divs_with_given_class as $single_div_with_given_class) {
foreach ($single_div_with_given_class->children() as $children) {
if ($children->tag == 'tag-you-are-searching-for') {
$output [] = $children->plaintext; //or whatever you want
}
}
}
... PHP DOM/xpath:
$all_divs_with_given_class =
$xpath->query("//div[@class='with-given-class']/tag-you-are-searching-for");
if (!is_null($all_divs_with_given_class)) {
foreach ($all_divs_with_given_class as $tag-you-are-searching-for) {
$ouput [] = $tag-you-are-searching-for->nodeValue; //or whatever you want
}
}
, "/" xpath .