I am trying to find child nodes by a certain class name (divs with class name=’foo’) within a loop of DOMDocument nodes. If it exists it should set my foo value to 1:
My HTML $document looks like:
...
<div class="posts">Div Posts 1</div>
<div class="posts">Div Posts 2<div class="foo"></div></div>
<div class="posts">Div Posts 3</div>
<div class="posts">Div Posts 4<div class="foo"></div></div>
<div class="posts">Div Posts 5</div>
...
DOMDocument/Xpath ($document):
$html = array();
$document = new \DOMDocument();
$document->loadHTMLFile($url); // loads html from above
$xpath = new \DOMXPath($document);
$i=0;
foreach ($xpath->query(Parser::cssToXpath('.posts')) as $node) {
$html['posts'][$i]['content'] = $node->nodeValue;
// check if child node with class name 'foo' exists => doesn't work :(
$children = $node->getElementsByTagName('foo');
if($children)
$html['posts'][$i]['foo'] = '1';
else
$html['posts'][$i]['foo'] = '0';
$i++;
}
Output:
[posts] => Array
(
[0] => Array
(
[content] => Div class Posts 1
[foo] => 1
)
[1] => Array
(
[content] => Div class Posts 2
[foo] => 1
)
[2] => Array
(
[content] => Div class Posts 3
[foo] => 1
)
[3] => Array
(
[content] => Div class Posts 4
[foo] => 1
)
[4] => Array
(
[content] => Div class Posts 5
[foo] => 1
)
)
getElementsByTagName() might not be the right method for that, but I tried different methods already and don’t find the right one. 🙁
According to your comment
to the previous answer your predicate is probably:
a) select div elements
b) with attribute class=posts
c) and with a child element div
d) which has attribute class=foo
as xpath expression:
a) //div
b) //div[ @class=”posts” ]
c) //div[ @class=”posts” and div ]
d) //div[ @class=”posts” and div[ @class=”foo” ] ]
e.g.
prints