PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

SimpleXMLElement->__construct> <SimpleXMLElement->attributes
Last updated: Fri, 05 Sep 2008

view this page in

SimpleXMLElement->children

(No version information available, might be only in CVS)

SimpleXMLElement->childrenFindet Kindelemente des gegebenen Knotens

Beschreibung

SimpleXMLElement
SimpleXMLElement children ([ string $ns [, bool $is_prefix ]] )

Die Methode findet Kinder des Elements, dem es angehört. Das Ergebnis entspricht den normalen Iterierungsregeln.

Hinweis: SimpleXML definiert für die meisten Methoden Regeln für das Hinzufügen von iterativen Eigenschaften. Diese können weder mit var_dump() oder auf andere Weise angezeigt werden.

Parameter-Liste

ns

is_prefix

Standardmäßig auf FALSE gesetzt.

Rückgabewerte

ChangeLog

Version Beschreibung
5.2.0 Der optionale Parameter is_prefix wurde hinzugefügt.

Beispiele

Beispiel #1 Durch ein children() Pseudo-Array traversieren

<?php
$xml 
= new SimpleXMLElement(
'<person>
 <child role="Sohn">
  <child role="Tochter"/>
 </child>
 <child role="Tochter">
  <child role="Sohn">
   <child role="Sohn"/>
  </child>
 </child>
</person>'
);

foreach (
$xml->children() as $second_gen) {
    echo 
' Die Person zeugte eine/n ' $second_gen['role'];

    foreach (
$second_gen->children() as $third_gen) {
        echo 
', die/der eine/n ' $third_gen['role'] . ' zeugte;';

        foreach (
$third_gen->children() as $fourth_gen) {
            echo 
' und diese/r ' $third_gen['role'] .
                
' zeugte eine/n ' $fourth_gen['role'];
        }
    }
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

 Die Person zeugte eine/n Sohn, die/der eine/n Tochter zeugte; Die Person zeugte
 eine/n Tochter, die/der eine/n Sohn zeugte; und diese/r Sohn zeugte eine/n Sohn



add a note add a note User Contributed Notes
SimpleXMLElement->children
Anonymous
06-Sep-2008 05:39
for XML namespaces such as <dc:creator> in RSS feeds use

<?php
    $xml
= new SimpleXMLElement($string);
   
$item = $xml->channel[0]->item[0];
   
$dc = $item->children("http://purl.org/dc/elements/1.1/");
    echo
$dc->creator;
?>
transglobe at gmx dot de
19-Mar-2008 03:37
I made a slightly differnt approch towards the RecurseXML function. Beeing hungry I had problems with the code, as it did just overwrite two <maincourse>s. So here is what I did:

<?php

$xml
= new SimpleXMLElement(
'<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>
        <part>ships</part>
        <part>steak</part>
     </maincourse>
     <maincourse>
        <part>fisch</part>
        <part>rice</part>
     </maincourse>
     <maincourse>
        <part>wine</part>
        <part>cheese</part>
     </maincourse>
   </menu>
</meal>'
);

$vals = array();
RecurseXML($xml,$vals);

foreach(
$vals as $key=>$value)
  print(
"{$key} = {$value}<BR>\n");

function
RecurseXML($xml,&$vals,$parent="") {

 
$childs=0;
 
$child_count=-1; # Not realy needed.
 
$arr=array();
        foreach (
$xml->children() as $key=>$value) {
                if (
in_array($key,$arr)) {
                       
$child_count++;
                } else {
                       
$child_count=0;
                }
               
$arr[]=$key;
               
$k=($parent == "") ? "$key.$child_count" : "$parent.$key.$child_count";
               
$childs=RecurseXML($value,$vals,$k);
                if (
$childs==0) {
                       
$vals[$k]= (string)$value;
                }
        }

  return
$childs;
}

?>
Output is like this:
type.0 = Lunch
time.0 = 12:30
menu.0.entree.0 = salad
menu.0.maincourse.0.part.0 = ships
menu.0.maincourse.0.part.1 = steak
menu.0.maincourse.0 =
menu.0.maincourse.1.part.0 = fisch
menu.0.maincourse.1.part.1 = rice
menu.0.maincourse.1 =
menu.0.maincourse.2.part.0 = wine
menu.0.maincourse.2.part.1 = cheese
menu.0.maincourse.2 =
menu.0 =

(Not beautiful, but it solved my case...)
crescentfreshpot at yahoo dot com
10-Dec-2007 08:16
Just a warning that the iterable returned from children() contains the '@attributes' key, which is "invisible" during a foreach but can be seen if using a different construct, such as list()=each() or casting to an array before iterating w/ foreach.
lars dot a dot johansson at se dot atlascopco dot com
20-Nov-2007 10:41
Hi,
Anyone who can tell me how to parse an xml tag that contains both text and childs. e.g.
...<sql>select * from table;<conv>default.php</conv><sql>...

The only way I could extract the text (select...) was with the following snippet

foreach($xml->children() as $k => $v ) {
$elem = count($v);
$xmla = (array) $xml[0];
if (is_string($xmla["$k"]) and $elem) {
    // $xmla["$k"] is 'select * from table'
}
...}
which is not very pretty.
Convert the child xml object to an array and check if the child is a string and not an end node. It's un ugly hack, but it does the job.
aero
23-May-2007 08:35
Here's a slightly modified function that transforms xml data into an associative array with the indices's into the array have the following syntax, parent.child etc.

So for

<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>steak</maincourse>
   </menu>
</meal>

The array would look like this...

array(4) {
  ["type"]=>
  string(5) "Lunch"
  ["time"]=>
  string(5) "12:30"
  ["menu.entree"]=>
  string(5) "salad"
  ["menu.maincourse"]=>
  string(5) "steak"
}

Here's an example

<?php

$xml
= new SimpleXMLElement(
'<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>steak</maincourse>
   </menu>
</meal>'
);

$vals = array();
RecurseXML($xml,$vals);

foreach(
$vals as $key=>$value)
  print(
"{$key} = {$value}<BR>\n");

function
RecurseXML($xml,&$vals,$parent="")
{
  
$child_count = 0;
   foreach(
$xml as $key=>$value)
   {
     
$child_count++;    
     
$k = ($parent == "") ? (string)$key : $parent . "." . (string)$key;
      if(
RecurseXML($value,$vals,$k) == 0// no childern, aka "leaf node"
        
$vals[$k] = (string)$value;  
   }
   return
$child_count;
}

The output:

type = Lunch
time
= 12:30
menu
.entree = salad
menu
.maincourse = steak

?>
aero
23-May-2007 08:07
Here's a simple, recursive, function to transform XML data into pseudo E4X syntax ie. root.child.value = foobar

<?php
error_reporting
(E_ALL);

$xml = new SimpleXMLElement(
'<Patriarch>
   <name>Bill</name>
   <wife>
     <name>Vi</name>
   </wife>
   <son>
     <name>Bill</name>
   </son>
   <daughter>
     <name>Jeri</name>
     <husband>
       <name>Mark</name>
     </husband>
     <son>
       <name>Greg</name>
     </son>
     <son>
       <name>Tim</name>
     </son>    
     <son>
       <name>Mark</name>
     </son>    
     <son>
       <name>Josh</name>
         <wife>
           <name>Kristine</name>
         </wife>
         <son>
           <name>Blake</name>
         </son>
         <daughter>
           <name>Liah</name>
         </daughter>
     </son>
   </daughter>
</Patriarch>'
);

RecurseXML($xml);

function
RecurseXML($xml,$parent="")
{
  
$child_count = 0;
   foreach(
$xml as $key=>$value)
   {
     
$child_count++;    
      if(
RecurseXML($value,$parent.".".$key) == 0// no childern, aka "leaf node"
     
{
         print(
$parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");       
      }    
   }
   return
$child_count;
}

?>

The output....

.name = Bill
.wife.name = Vi
.son.name = Bill
.daughter.name = Jeri
.daughter.husband.name = Mark
.daughter.son.name = Greg
.daughter.son.name = Tim
.daughter.son.name = Mark
.daughter.son.name = Josh
.daughter.son.wife.name = Kristine
.daughter.son.son.name = Blake
.daughter.son.daughter.name = Liah
taylorbarstow at that google mail thingy
21-Apr-2006 07:38
Sometimes you actually want an array, not a pseudo array.   This is especially true when you aren't dealing with attributes (i.e., you just want the array of child nodes).

Do like this:

<?php
$children
= $sxml->xpath('child::node()');
?>

The reason you might want this is to be able to use array functions like array_shift, array_pop, etc.  This is especially true when you are writing recursive functions.  Simplexml works really well in iterative programming, but if you try to implement recursion it gets ugly.
Sebastian
27-Oct-2005 03:45
Just a quick addition:

If you need to access a child node which contains a dash, you need to encapsulate it with {""}.

For example:
<?php
foreach ($domain->domain-listing as $product) {
}
?>

The example above doesn't work because of the dash. But instead you need to use:
<?php
foreach ($domain->{"domain-listing"} as $product) {
}
?>

At least for me the second example works perfectly fine.
no-one
31-May-2005 06:05
For anyone who hasn't read Sterling Hughe's article (http://www.zend.com/php5/articles/php5-simplexml.php):

<?php
$xml_document
=<<<EOT
<?xml version="1.0"?>
<root xmlns:foo="http://google.com">
  <foo:bar>baz</foo:bar>
</root>
EOT;

$xml_document = simplexml_load_xml($xml_document);

$foo_ns_bar = $xml_document->children('http://google.ca');

echo
$foo_ns_bar->bar[0]; // prints 'baz'
?>
Andrew Rose (rose dot andrew at gmail dot com)
16-Mar-2005 04:48
The example below shows the basic use of depth-first recursion to span the xml tree.

This is coded for the command line, and it prints out the original sentance above and then the copy cat sentence it creates itself for comparison, which as you will see; this example is slightly off from, I'll leave it upto you to resolve this issue.

All in all I personaly think xml and recursion go hand in hand, so if you don't understand recursion but know xml and want to use php to manipulate xml you will need to learn about recursion at some point.

<?
$xml
= simplexml_load_string(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>'
);

function
recurse($child)
 {
   foreach(
$child->children() as $children) {
     echo
' who begot a '.$children['role'];
    
recurse($children);
   }
    return;
 }

foreach(
$xml->children() as $children) {
 echo
'The person begot a '.$children['role'];
 
recurse($children, 0);
 echo
'; ';
}

echo
"\n";
echo
'The person begot a son who begot a daughter; The person begot a daughter who begot a son; and that son begot a son'."\n";

?>
zyxwvu at users dot sourceforge dot net
15-Feb-2004 10:32
File:

<category>
  <item>text</item>
  <bold>text</bold>
  <item>text</item>
  <item>text</item>
  <mark>text</mark>
  <bold>text</bold>
</category>

If you want to get also names of the tags, you can use this loop layout:

foreach($category -> children() as $name => $node){
  echo $name.'<br/>';
}

 
show source | credits | sitemap | contact | advertising | mirror sites