2010-08-05 60 views
0

我有一個虛擬的XML這樣的:的SimpleXML和相同的孩子

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

我通過XML要循環,我的問題是:如何循環槽重複的孩子呢?例如區域名稱爲Area1的循環區域? (有2區域1與中心1和中心2,我想做出這樣的查詢:找出所有中心那個區域是區域1) 預先感謝

+2

也許這只是我,但我不明白的問題。你想實現什麼? – VolkerK 2010-08-05 11:29:59

+0

我沒有看到問題。這是有效的XML,爲什麼它不工作? – Gaim 2010-08-05 11:33:26

+0

我編輯了我的問題。感謝您的幫助 – TheNone 2010-08-05 11:36:33

回答

4

<水晶球> 也許你要遍歷有所有cities元素一個area元素與文本內容Area1 < /水晶球>
您可以使用XPath爲例如

<?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>'); 
} 

打印

area: Area1 
period: period1 
center: center1 
area: Area1 
period: period1 
center: center2 
+0

謝謝!最後一個例子,我可以拿起和理解零碎。 :) – 2010-08-05 18:20:49

2

是當然的。例如讀取PHP的XPath手動

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 
}