0

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

5
  • 2
    Maybe it's just me but I don't get the question. What do you want to achieve? Commented Aug 5, 2010 at 11:29
  • I don't see the problem. This is valid XML so why shouldn't it work? Commented Aug 5, 2010 at 11:33
  • Do you want loop through all children or only through repeated? Commented Aug 5, 2010 at 11:39
  • there is 2 Area1 with center1 and center2, I want make a query like this : find all center that area is Area1 Commented Aug 5, 2010 at 11:39
  • 1
    The soluion is XPath Query: //cities[area=='Area1'] This XPath returns all cities which has tag area equal to Areal1. Is it alright? Commented Aug 5, 2010 at 11:43

2 Answers 2

4

<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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Finally an example I can pick up and understand piecemeal. :)
2

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.