问题描述:

I have a xml document, i need to get name attribute's value with helping php. the xml file looks like this:

<?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>

please help me i dont know what to do.. sorry for my english.

网友答案:

You can use DOMDocument to parse that XML and get all items using DOMXpath, then loop in all items and get the attributes based on position (id = 0, name = 2), then create an new array that will hold all you item id's with their names:

$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

Codepad Example

相关阅读:
Top