You might want to use simplexml_load_string()
, then register your namespaces with registerXPathNamespace()
and then you can start to adress your items by using xpath()
.
Then you are able to use these namespaces to adress the items correctly in your xpath query.
<?php
$xml = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<addItemToShoppingCartResponse xmlns="http://www.sample.com/services">
<ack>Warning</ack>
</addItemToShoppingCartResponse>
</soapenv:Body>
</soapenv:Envelope>
';
$xml = simplexml_load_string($xml, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
// register your used namespace prefixes
$xml->registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('services', 'http://www.sample.com/services'); // ? ns not in use
// then use xpath to adress the item you want (using this NS)
$nodes = $xml->xpath('/soapenv:Envelope/soapenv:Body/services:addItemToShoppingCartResponse/services:ack');
$ack = (string) $nodes[0];
var_dump($ack);
Question from comments:
"What if i file have subnodes in addItemToShoppingCartResponse node? How to apply foreach loop?"
Answer
Use xpath to travel and select the node, which is one level above your items. Here it's "ship". You will get all the items underneath ship. Then might use an foreach iteration to get the content.
Note: Nodes are always "lists/arrays" - so you need the [0]
. But you see that, when using var_dump()
, too.
// example data looks like this
// addItemToShoppingCartResponse -> ship -> item
$xml = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<addItemToShoppingCartResponse xmlns="http://www.sample.com/services">
<ack>warrning</ack>
<ship>
<item>231</item>
<item>232</item>
</ship>
</addItemToShoppingCartResponse>
</soapenv:Body>
</soapenv:Envelope>
';
// load xml like above + register NS
// select items node (addItemToShoppingCartResponse -> ship)
$items = $xml->xpath('/soapenv:Envelope/soapenv:Body/services:addItemToShoppingCartResponse/services:ship/services:item');
// iterate item nodes
foreach ($items as $item)
{
//var_dump($item);
echo (string) $item[0];
}