0

我有一个 xml 文档,我需要通过帮助 php 来获取 name 属性的值。xml 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:GetGoodsTreeResponse xmlns:ns2="http://b2b.alta.com.ge" xmlns:ns3="http://192.168.0.10/b2b">
         <ns3:GoodsTree level="0">
            <item id="010000000017337" level="0" name="COMPUTERS" is_open="N">
               <item id="015000000030431" level="1" name="ALTA" is_open="Y">
                  <item id="015000000030443" level="2" name="Zakaznoe Izdelie" is_open="N"/>
                  <item id="015002000031034" level="2" name="ATOM" is_open="N"/>
                  <item id="015005000030453" level="2" name="Celeron" is_open="N"/>
                  <item id="015010000030432" level="2" name="Dual Core" is_open="N"/>
                  <item id="015150000030778" level="2" name="i3" is_open="N"/>
                  <item id="015220000030775" level="2" name="i5" is_open="N"/>
                  <item id="015300000031827" level="2" name="i7" is_open="N"/>
               </item>
               <item id="010001005030300" level="1" name="Apple" is_open="N"/>
               <item id="010001001033496" level="1" name="Asus" is_open="N"/>
               <item id="010001001015793" level="1" name="Fujitsu" is_open="N"/>
               <item id="010001002015166" level="1" name="HP Compaq" is_open="N"/>
            </item>
          </ns3:GoodsTree>
      </ns2:GetGoodsTreeResponse>
   </S:Body>
</S:Envelope>

请帮助我,我不知道该怎么做..对不起我的英语。

4

1 回答 1

2

您可以使用DOMDocument解析该 XML 并获取所有项目DOMXpath,然后循环所有项目并根据位置(id= 0,name= 2)获取属性,然后创建一个新数组,该数组将包含所有项目 ID 及其名称:

$dom = new DOMDocument;
$dom->loadXML($xml);

$xpath = new DOMXPath($dom);
$xpath->registerNamespace('S', 'http://schemas.xmlsoap.org/soap/envelope/');

$items = array();

$el = $xpath->query('//item');
foreach($el as $item){
    $attributes = $item->attributes; 
    $items[$attributes->item(0)->value] = $attributes->item(2)->value;
}

var_dump($items); // $items will be an array with item id and it's value will be item name

键盘示例

于 2012-10-06T20:29:31.273 回答