tags:

views:

31

answers:

2

I have a dummy xml like this:

<SOA>
<cities>
    <area>Area1</area>
    <period>period1</period>
    <center>center1</center>
</cities>
<cities>
    <area>Area1</area>
    <period>period1</period>
    <center>center2</center>
</cities>
<cities>
    <area>Area2</area>
    <period>period1</period>
    <center>center3</center>
</cities>
</SOA>

I want to loop through the xml, my question is: How can I loop trough repeated child? e.g loop through area that area name is Area1 ? (there is 2 Area1 with center1 and center2, I want make a query like this : find all center that area is Area1) Thanks in advance

+4  A: 

<crystal ball> Maybe you want to iterate over all cities elements that have a area element with the text content Area1 </crystal ball>
You can use XPath for that, e.g.

<?php
$soa = getDoc();
foreach( $soa->xpath('cities[area="Area1"]') as $ci ) {
  foreach( $ci->children() as $child ) {
    echo $child->getName(), ': ', (string)$child, "\n";  
  }
}

function getDoc() {
  return new SimpleXMLElement('<SOA>
    <cities>
      <area>Area1</area>
      <period>period1</period>
      <center>center1</center>
    </cities>
    <cities>
      <area>Area1</area>
      <period>period1</period>
      <center>center2</center>
    </cities>
    <cities>
      <area>Area2</area>
      <period>period1</period>
      <center>center3</center>
      </cities>
    </SOA>');
}

prints

area: Area1
period: period1
center: center1
area: Area1
period: period1
center: center2
VolkerK
Thank you! Finally an example I can pick up and understand piecemeal. :)
mjboggess
+2  A: 

Yes of course. Read for example php XPath manual

http://php.net/manual/en/simplexmlelement.xpath.php

$xml = new SimpleXMLElement($yourXML);

$result = $xml->xpath('/SOA/cities/SOA/cities[area="Area1"]');

while(list( , $node) = each($result)) {
    //$node is a city node with Area1 area
}
Tomasz Struczyński