2013-02-27 150 views
1

這裏是我的XML數據的〔實施例:如何獲取元素值爲1的所有元素名稱到數組中?

<features> 
    <bedrooms>1</bedrooms> 
    <bathrooms>1</bathrooms> 
    <ensuite></ensuite> 
</features> 

我訪問這個像這樣:

$data->features; 

我基本上要使它所以它遍歷,如果它有一個1它將它添加到數組中。

然後,我可以破滅,並得到下面的結果:

bedrooms, bathrooms 

套房,因爲它沒有一個不存在以上。

我該如何循環並將其添加到數組?

我已經試過:

foreach($data->features as $key => $val){ 
    $features[] = $val; 
} 

,但不起作用。

謝謝。

回答

0

使用的SimpleXML:

$lib = simplexml_load_file("test.xml"); 
$children = $lib->children()[0]; 
$features = array(); 

foreach($children as $node){ 
    $features[] = $node->title; 
} 

print_r($features); 
1
foreach($data->features as $child){ 
    foreach ($child as $k => $v){ 
     if ($v == 1){ 
      $features[] = $k; 
     } 
    } 
} 

這似乎是工作,但它是一個很好的方式?

+1

看起來像遍歷XML結構就好。這是你將不得不做的,看看哪些設置爲1,哪些不是。 – Husman 2013-02-27 10:08:24

+0

這樣做絕對沒問題。您還可以使用[XPath](http://schlitt.info/opensource/blog/0704_xpath.html)查詢包含nodeValue的節點,例如,做$ foreach($ features-> xpath('* [text()= 1]')爲$ feature){$ elementNames [] = $ feature-> getName(); }' – Gordon 2013-02-27 10:40:39