PHP Doku:: Checks if node has children - domnode.haschildnodes.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzXML-ManipulationDocument Object ModelThe DOMNode classDOMNode::hasChildNodes

Ein Service von Reinhard Neidl - Webprogrammierung.

The DOMNode class

<<DOMNode::hasAttributes

DOMNode::insertBefore>>

DOMNode::hasChildNodes

(PHP 5)

DOMNode::hasChildNodes Checks if node has children

Beschreibung

bool DOMNode::hasChildNodes ( void )

This function checks if the node has children.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Siehe auch


3 BenutzerBeiträge:
- Beiträge aktualisieren...
sansana
15.10.2010 4:04
Personally I think using a simple:[code]if($DOMNode->childNodes <>0){}[/code] works better.
syngcw at syncgw.com
4.01.2010 14:53
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
jintoppy at gmail dot com
28.04.2009 13:13
<?php

$doc
= new DOMDocument;
$node = $doc->createElement("FirstMain", "First Main Node. This have child");
$doc->appendChild($node);
$childnode = $doc->createElement("childnode", "child node");
$node->appendChild($childnode);
$secondnode = $doc->createElement("SecondMain", "First Main Node. This don't have child");
$doc->appendChild($secondnode);
$doc->saveXML();
$nodeElmt = $doc->getElementsByTagName("FirstMain");
/*
if given as $nodeElmt = $doc->getElementsByTagName("childnode");
the output would be "This node has childnodes"

if given as $nodeElmt = $doc->getElementsByTagName("SecondMain");
the output would be "This node has no childnodes"

*/

foreach($nodeElmt as $nodeElmt)
{
if(
$nodeElmt->hasChildNodes())
{
echo
"This node has childnodes";
}
else
{
echo
"This node has no childnodes";
}
}

 
?>

- - - - - - - - - - - - - -

Output:

This node has childnodes

- - - - - - - - - - - - - -



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)