2011-11-11 25 views
0

我正在閱讀使用PHP簡單xml的XML文件。 I循環顯示包含節點數據的每個類別節點,具體取決於所選類別,從而顯示子類別。我需要檢測某個類別何時沒有子類別。我需要的可能是將所有parent_id節點放入數組中,然後查看cat_id是否在數組中,以檢測它是否有任何依賴項。php - simpleXML將相同的節點放入數組

$cat_xml = simplexml_load_file(XML_PATH.'categories/'. $clientID . '.xml'); 

      //get all the categories and go through each one 
      foreach($cat_xml as $cat){ 
       if (//WHAT GOES HERE??){ 
        //display if cat is top level or has been selected 
        if ($cat->parentID == $cat_parent_id){ 
         //check product isn't set to hidden 
         if ($cat->visible == 1){ 
          echo '<div class="catbox">'; 
           echo "<a href=\"index.php?pageID=$pageID&cat_parent_id=$cat->id&cat_name=$cat->Name\"> $cat->Name </a><br />"; 
          echo '</div>'; 
         } 
        } 
       } else { 
        echo '<p>There are no sub categories.</p>'; 
       } 
      } 

[編輯]
的XML低於和我需要「的parentID」的值的數組

<categories> <category> <id>740073</id> <Name>Leetee Cat 1</Name> <parentID>0</parentID> <Description><![CDATA[Charlotte Balbier Weddinhg <em>dresses</em>,<strong> blah blah blah!!<br /> </strong>]]></Description> <imageURL>alice-charlotte-balbier-english-tea-party-collection-2011.jpg</imageURL> <sequence>0</sequence> <visible>1</visible> </category> 
+1

聽起來像你需要XPath –

+0

請顯示XML片段,並澄清你究竟需要從中解析什麼。 – Gordon

+0

我已將XMl添加到原始問題 - 謝謝 – LeeTee

回答

1

XPath可用於搜索包含的父ID的類別當前類別。

foreach($cat_xml as $cat) { 
    $cat_id = intval($cat->id); 
    // Find categories that call this one their parent 
    $child_cats = $cat_xml->xpath("/categories/category[parentID/text()={$cat_id}]"); 
    if (!empty($child_cats)){ 
     //display if cat is top level or has been selected 
     if ($cat->parentID == $cat_parent_id){ 
      // .... 
     } 
    } else { 
     echo '<p>There are no sub categories.</p>'; 
    } 
}