2011-05-12 111 views
0

我想解析一個包含簡單訂單表單內容的xml文件。我很舒服解析這將有這樣內容的XML文件:使用PHP解析元素中的xml元素

<list> 
    <item> 
    <id>1</id> 
    <quantity>14</quantity> 
    </item> 

    <item> 
    <id>2</id> 
    <quantity>3</quantity> 
    </item> 
</list> 

現在我想能夠解析的結構,像這樣的XML文件。這個文件被命名爲「order.xml」以備將來參考。

<main> 
<user> 
    <address>123 Fake Street, City, STATE, ZIP</address> 
    <list> 
     <item> 
      <id>1</id> 
      <quantity>3</quantity> 
     </item> 
     <item> 
      <id>3</id> 
      <quantity>4</quantity> 
     </item> 
    </list> 
</user> 

<user> 
    <address>246 Fake Street, City, STATE, ZIP</address> 
    <list> 
     <item> 
      <id>2</id> 
      <quantity>4</quantity> 
     </item> 
     <item> 
      <id>3</id> 
      <quantity>4</quantity> 
     </item> 
    </list> 
</user> 

</main> 

爲此我使用解析文件的PHP代碼是這樣:

<?php 
    // load SimpleXML 
    $main = new SimpleXMLElement('order.xml', null, true); 
    $list = $main; 
    print("<table border = '1'> 
    <tr> 
     <th>Address</th> 
     <th>Item_id</th> 
     <th>Quantity</th> 
    </tr> "); 
    foreach($main as $user) // Loops through the users 
    { 
     print ("<tr> 
      <td>{$user->address}</td>"); 
     foreach($list as $item) 
     { 
      print ("<td>{$item->id}</td> 
     <td>{$item->quantity}</td></tr>"); 
     } 
    } 
    echo '</table>'; 
?> 

因此對於輸出,我想PHP腳本創建一個表像下,但在HTML表格中正確格式化以便於觀看。:

 
     Address Item_id Quantity 
     Address 1 2   3 
     Address 1 3   4 
     Address 2 1   1 

非常感謝您提前!

+0

因此鬆了一口氣,打開這個問題,看到你正在使用正確的工具。 – 2011-05-12 23:22:49

回答

1
<?php 
    // load SimpleXML 
    $main = new SimpleXMLElement('order.xml', null, true); 
    print("<table border = '1'> 
    <tr> 
     <th>Address</th> 
     <th>Item_id</th> 
     <th>Quantity</th> 
    </tr> "); 
    foreach($main->user as $user) // Loops through the users 
    { 
     print ("<tr> 
      <td>{$user->address}</td>"); 
     foreach($user->item as $item) 
     { 
      print ("<td>{$item->id}</td> 
     <td>{$item->quantity}</td></tr>"); 
     } 
    } 
    echo '</table>'; 
?> 
+0

出於某種原因,腳本將顯示每行的地址,但它將拒絕顯示物品ID和數量。我有點難以忍受這 – JR90 2011-05-12 23:32:41

+1

它應該可能是$ user-> list-> item而不是$ user-> item – Kibbee 2011-05-12 23:46:31

+0

James有它的權利,但只是一個小的疏忽。 $ user沒有item屬性,只有一個list屬性。所以在內部之前,你需要'$ list = $ user-> list'。然後這個for變成'foreach($ list-> item as $ item)'...... – 2011-05-12 23:48:37