PHP Function Reference

PHP SimpleXMLElement - children() Method



The PHP SimpleXMLElement::children() method finds the children of an element. The result follows normal iteration rules.

Syntax

public SimpleXMLElement::children(namespaceOrPrefix, isPrefix)

Parameters

namespaceOrPrefix Optional. Specify an XML namespace.
isPrefix Optional. If true, namespaceOrPrefix will be regarded as a prefix. If false, namespaceOrPrefix will be regarded as a namespace URL.

Return Value

Returns a SimpleXMLElement element, whether the node has children or not.

Example: traversing a children()

The example below shows the usage of SimpleXMLElement::children() method.

<?php
$xmlstr = <<<XML
<userlist> 
  <user id="John123" game="lonely">
    <name>John Smith</name>
    <city>New York</city>
  </user>
  
  <user id="Marry2015" game="group">
    <name>Marry G.</name>
    <city>London</city>
  </user>

  <user id="Gaurav" game="group">
    <name>Gaurav K.</name>
    <city>India</city>
  </user>   
</userlist> 
XML;

$xml = simplexml_load_string($xmlstr);

//displaying the id children
foreach ($xml->children() as $x) {
  echo $x['id']."\n";
}

echo "\n";

//displaying the whole SimpleXMLElement element
foreach ($xml->children() as $x) {
  var_dump($x);
}
?>

The output of the above code will be similar to:

John123
Marry2015
Gaurav

object(SimpleXMLElement)#5 (3) {
  ["@attributes"]=>
  array(2) {
    ["id"]=>
    string(7) "John123"
    ["game"]=>
    string(6) "lonely"
  }
  ["name"]=>
  string(10) "John Smith"
  ["city"]=>
  string(8) "New York"
}
object(SimpleXMLElement)#4 (3) {
  ["@attributes"]=>
  array(2) {
    ["id"]=>
    string(9) "Marry2015"
    ["game"]=>
    string(5) "group"
  }
  ["name"]=>
  string(8) "Marry G."
  ["city"]=>
  string(6) "London"
}
object(SimpleXMLElement)#5 (3) {
  ["@attributes"]=>
  array(2) {
    ["id"]=>
    string(6) "Gaurav"
    ["game"]=>
    string(5) "group"
  }
  ["name"]=>
  string(9) "Gaurav K."
  ["city"]=>
  string(5) "India"
}

Example: using namespaces

Consider one more example where this method is used XML data containing namespaces.

<?php
$xmlstr = <<<XML
<userlist xmlns:p="player.data"> 
  <p:user>John Smith</p:user>
  <user>Marry G.</user>
  <p:user>Gaurav K.</p:user>   
</userlist> 
XML;

$xml = simplexml_load_string($xmlstr);

//number of children with 'p' as namespace
$player = $xml->children('p');
var_dump(count($player));

//number of children with 'p' as prefix
$player = $xml->children('p', TRUE);
var_dump(count($player));

//number of children with 'player.data' as namespace
$player = $xml->children('player.data');
var_dump(count($player));

//number of children with 'player.data' as prefix
$player = $xml->children('player.data', TRUE);
var_dump(count($player));

//number of children without any namespace or prefix
$player = $xml->children();
var_dump(count($player));
?>

The output of the above code will be similar to:

int(0)
int(2)
int(2)
int(0)
int(1)

❮ PHP SimpleXML Reference