2013-09-29 168 views
0

PHP XPath查詢:XPath查詢返回的多個節點

$query = $xpathvar->query('//siri:Service'); 
foreach($query as $service) { 
    echo $service->textContent; 
    // Here I need to also echo this Vehicle's reg 
} 

針對性的XML:

<Vehicle> 
    <CategoryA> 
     <Service>123123123</Service> 
    </CategoryA> 
    <CategoryB> 
     <SubCategoryA> 
      <Reg>ASDF_XC1</Reg> 
     </SubCategoryA> 
    </CategoryB> 
</Vehicle> 
// Imagine many more vehicles here each with a service and reg 

我怎樣才能改變PHP,這樣我也找回了reg爲每一個以及? Service和Reg必須在檢索時位於同一輛車內(不是隨機對)。

+0

你的問題是不是真的清楚。根據XML結構,Reg應該已經成爲'textContent'的一部分。 – hakre

回答

3

如何查詢車輛,然後使用它作爲上下文節點來搜索ServiceReg

$vehicles = $xpath->query('//siri:Vehicle'); 
$pairs = array(); 
foreach ($vehicles as $vehicle) { 
    $pairs[] = array(
     'Service' => $xpath->evaluate('string(.//siri:Service)', $vehicle), 
     'Reg'  => $xpath->evaluate('string(.//siri:Reg)' , $vehicle), 
    ); 
} 

看得那麼清楚:

+0

非常完美,非常感謝! – jskidd3