PHP 8.5.0 Alpha 2 available for testing

DOMNode::hasChildNodes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasChildNodes Проверяет, имеет ли данный узел потомков

Описание

public DOMNode::hasChildNodes(): bool

Эта функция проверяет, содержит ли данный узел потомков.

Список параметров

Сигнатура функции не содержит параметров.

Возвращаемые значения

Функция возвращает true, если выполнилась успешно, или false, если возникла ошибка.

Смотрите также

Добавить

Примечания пользователей 4 notes

up
6
sansana
14 years ago
Personally I think using a simple:[code]if($DOMNode->childNodes <>0){}[/code] works better.
up
6
syngcw at syncgw.com
15 years ago
This function is a bit tricky. If you want to find XML childnodes it is useless. You need to create a work-around:

<?php

$x
= new DOMDocument();
$x->loadXML('
<A>
<B>b-text</B>
<C>
<D>d-text</D>
</C>
<E/>
</A>'
);

shownode($x->getElementsByTagName('A')->item(0));
function
shownode($x) {
foreach (
$x->childNodes as $p)
if (
hasChild($p)) {
echo
$p->nodeName.' -> CHILDNODES<br>';
shownode($p);
} elseif (
$p->nodeType == XML_ELEMENT_NODE)
echo
$p->nodeName.' '.$p->nodeValue.'<br>';
}
function
hasChild($p) {
if (
$p->hasChildNodes()) {
foreach (
$p->childNodes as $c) {
if (
$c->nodeType == XML_ELEMENT_NODE)
return
true;
}
}
return
false;
}

?>

shows:
B b-text
C -> CHILDNODES
D d-text
E
up
4
richard dot gildx at gmail dot com
12 years ago
This "hasChildNodes()" exercise is simple enough to make it clear and understandable. Or, you could take it as a tag empty check. By Richard Holm, Sweden.

<?php
$xmldoc
=
'<?xml version="1.0" ?>
<root>
<text>Text</text>
<none/>
<empty></empty>
<space> </space>
</root>'
;

$domdoc=new DOMDocument();
$domdoc->loadXML($xmldoc);

$tag=$domdoc->getElementsByTagName('root')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo
$tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('text')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo
$tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('none')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo
$tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('empty')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo
$tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('space')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo
$tag->tagName.$v."<br/>";
?>

Output:
root hasChildNodes
text hasChildNodes
none hasNoChildNodes
empty hasNoChildNodes
space hasChildNodes
up
-5
Anonymous
10 years ago
Hi what if its a dynamic file and we cannot use get elements by tag name then how do we print the contents of all level tags?
To Top