Can anyone help explain to me why the following is returning duplicate data?
<?php
$xml_test = '<array key="results">
<array key="123">
<string key="mask">1234</string>
</array>
<array key="987">
<string key="mask">5678</string>
</array>
</array>';
$load_test = simplexml_load_string($xml_test);
foreach ($load_test as $array)
{
$mask = $array->xpath('//string[@key="mask"]');
print 'Mask: ' . $mask[0] . '<br />';
}
Returns:
Mask: 1234
Mask: 1234
If I throw a print_r($array) within the foreach loop, I get:
SimpleXMLElement Object
(
[@attributes] => Array
(
[key] => 123
)
[string] => 1234
)
Mask: 1234
SimpleXMLElement Object
(
[@attributes] => Array
(
[key] => 987
)
[string] => 5678
)
Mask: 1234
What the hell is going on? Why am I getting duplicate masks when I use an xPath expression when both of the $array quite clearly are not holding duplicate data.
Starting the location path in
xpath()with/makes it “absolute”, whereas you want to query “relative” to the$arrayelement. For your example, just take out the//.See also http://www.sitepoint.com/forums/showthread.php?723058-php-xml-loop&p=4778177&viewfull=1#post4778177