2011-05-12 3 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

이 질문을 열고 당신이 직업에 적합한 도구를 사용하고 있는지 확인하십시오. –

답변

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

+1

$ user-> item 대신 $ user-> list-> item이되어야한다. – Kibbee

+0

James는 맞다. 그러나 작은 감독이있다. $ user에는 item 속성이없고 list 속성 만 있습니다. 그래서 내부 용으로'$ list = $ user-> list'가 필요합니다. 그러면 for는'foreach ($ item-> item $ item) '가됩니다. ... –