I need a to create an array with all the subject values in this XML file. The ISIN list seems to work fine (the first property value), but subject values does not work.
The main problem you've got is to find the child-element based on an attributes value. As there are multiple children with the same element name, you can not differ on the name alone.
In your concrete example the property child based on the attribute type2="isin".
This is either possible by making use of Xpath (this website already has a lot of Q&A material about that, for example SimpleXML: Selecting Elements Which Have A Certain Attribute Value) or by extending SimpleXMLElement
with a function that just does it:
class MyElement extends SimpleXMLElement
{
public function getChildByAttributeValue($name, $value) {
foreach($this as $child)
{
if ($value === (string) $child[$name]) {
return $child;
}
}
}
}
You can then use the MyElement
instead of the SimpleXMLElement
:
$xml = simplexml_load_string($buffer, 'MyElement');
###########
and just map your values to an array:
$map = function(MyElement $subject) {
return [
(string) $subject['value'],
(string) $subject->getChildByAttributeValue('type2', 'isin')['value'],
];
};
print_r(array_map($map, $xml->xpath('//subject')));
Given that $buffer
is the XML you have provided in question (and the encoding error removed), this creates the following output:
Array
(
[0] => Array
(
[0] => AAB
[1] => DK0010247014
)
[1] => Array
(
[0] => ALM BRAND
[1] => DK0015250344
)
[2] => Array
(
[0] => BAVARIAN NORDI
[1] => DK0015998017
)
[3] => Array
(
[0] => DFDS
[1] => DK0010259027
)
[4] => Array
(
[0] => FLSMIDTH & CO
[1] => DK0010234467
)
)
The full code example (Online Demo):
class MyElement extends SimpleXMLElement
{
public function getChildByAttributeValue($name, $value) {
foreach($this as $child)
{
if ($value === (string) $child[$name]) {
return $child;
}
}
}
}
$xml = simplexml_load_string($buffer, 'MyElement');
$map = function(MyElement $subject) {
return [
(string) $subject['value'],
(string) $subject->getChildByAttributeValue('type2', 'isin')['value'],
];
};
print_r(array_map($map, $xml->xpath('//subject')));