2010-01-21 46 views
1

下面我有一個簡單的XML:SimpleXML的是給我錯誤的結果

<?xml version="1.0" encoding="utf-8"?> 
<catalogue> 
    <category name="textbook" id="100" parent="books"> 
    <product id="20000"> 
     <author>Gambardella, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
    </product> 
    <product id="20001"> 
     <author>Gambardellas, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
    </product> 
    </category> 
    <category name="fiction" id="101" parent="books"> 
    <product id="2001"> 
     <author>Ralls, Kim</author> 
     <title>Midnight Rain</title> 
     <genre>Fantasy</genre> 
     <type>Fiction</type> 
     <price>5.95</price> 
     <publish_date>2000-12-16</publish_date> 
     <description>A former architect battles corporate zombies, an evil sorceress,     and her own childhood to become queen 
     of the world.</description> 
    </product> 
    </category> 
</catalogue> 

我使用PHP simplexml的庫來解析它,如下所示:(注意有兩個類別節點第一類包含兩個「。產品」的孩子。我的目標是獲得一個包含第一的那兩個孩子的數組‘類別’

$xml = simplexml_load_file($xml_file) or die ("unable to load XML File!".$xml_file); 

//for each product, print out info 
$cat = array(); 
foreach($xml->category as $category) 
{ 
    if($category['id'] == 100) 
    { 
     $cat = $category;  
     break; 
    } 
} 
$prod_arr = $category->product; 

這是問題所在。我期待着與這兩種產品的兒童,但其只返回一個產品陣列。什麼我是做錯了還是這是一個PHP的錯誤?請幫助!

回答

2

您可以使用SimpleXMLElement::xpath()來獲取在一個特定的類別元素的所有子產品元素。例如。

// $catalogue is your $xml 
$products = $catalogue->xpath('category[@id="100"]/product'); 
foreach($products as $p) { 
    echo $p['id'], ' ', $p->title, "\n"; 
} 

打印

20000 XML Developer's Guide 
20001 XML Developer's Guide 
1

首先,您的XML文件沒有很好的定義。你可能應該用 <categories>標籤來開始和結束它。

使用以下內容替換最後一個任務:

$prod_array = array(); 
foreach ($cat->product as $p) { 
    $prod_array[] = $p; 
} 
0
$cat = array(); 
foreach ($xml->category as $category) 
{ 
    $attributes = $category->attributes(); 
    if(isset($attributes['id']) && $attributes['id'] == 100) 
    { 
     $cat = $category; 
     break; 
    } 
} 
+0

永遠不要忘記埋怨代碼之前驗證XML文件。這很簡單,只需用firefox打開你的文件(或者在Linux下嘗試xmllint命令),它會告訴你錯誤出現在哪裏。 – OcuS 2010-01-21 08:22:58

+0

我根據你的編輯修復了我的代碼:) – OcuS 2010-01-21 08:28:12