开发者

simpleXML and the same child

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


<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


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜