XPath/Domdocument-check für Kinder von Klasse name
Ich bin auf der Suche nach Kind-Knoten von einem bestimmten Klassennamen (divs mit class name='foo') in einer Schleife des DOMDocument-Knoten. Wenn es vorhanden ist sollte es mein foo "den Wert" 1:
Meine HTML - $ - Dokument sieht wie folgt aus:
...
<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++;
}
Ausgabe:
[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() kann nicht die richtige Methode ist, aber ich habe versucht, verschiedene Methoden, die schon und nicht das richtige zu finden. 🙁
Du musst angemeldet sein, um einen Kommentar abzugeben.
Laut Ihrem Kommentar
zu der vorherigen Antwort, die Ihr Prädikat ist wahrscheinlich:
a) wählen Sie div-Elemente
b) mit dem Attribut class=Beiträge
c) und mit einem Kind-element div
d) das Attribut class=foo
als xpath-Ausdruck:
a) //div
b) //div[ @class="posts" ]
c) //div[ @class="posts" und div ]
d) //div[ @class="posts" und div[ @class="foo" ] ]
z.B.
Drucke
Verwenden Sie diese XPath finden Sie alle
div
Elemente mit der Klassefoo
Um genauer zu sein, verwenden Sie diese:
div
mit Klassefoo
nur, wenn Sie innerhalb vondiv
mit Klasseposts.
//div[@class = 'posts'][div[@class = 'foo']]
. Es wählt nurdiv.posts
enthältdiv.foo
.