I'm fetching some xml and convert it to csv similar to this post PHP - Fetch correct XML values if elements have similar tags per record. Some of the elements have attributes with values. How can I fetch them as well?
This is my structure:
XML File:
<abc:ABCData xmlns:abc="http://www.abc-example.com" xmlns:xyz="http:/www.xyz-example.com">
<abc:ABCRecords>
<abc:ABCRecord>
<abc:ABC>5EXZX4LPK</abc:ABC>
<abc:Entity type="Lorem" status="Lipsum">
<abc:Name>Bornheim</abc:Name>
</abc:Entity>
</abc:ABCRecord>
<abc:ABCRecord>
<abc:ABC>5967007LI</abc:ABC>
<abc:Entity type="Dolor" status="Amet">
<abc:Name>MOON BANK</abc:Name>
</abc:Entity>
</abc:ABCRecord>
</abc:ABCRecords>
</abc:ABCData>
PHP file:
<?php
$reader = new XMLReader();
$reader->open('php://stdin');
$output = fopen('php://stdout', 'w');
fputcsv($output, ['id', 'name']);
//fputcsv($output, ['id', 'type', 'status', 'name']);
$xmlns = [
'abc' => 'http://www.abc-example.com'
];
$dom = new DOMDocument;
$xpath = new DOMXpath($dom);
foreach ($xmlns as $prefix => $namespaceURI) {
$xpath->registerNamespace($prefix, $namespaceURI);
}
while (
$reader->read() &&
(
$reader->localName !== 'ABCRecord' ||
$reader->namespaceURI !== $xmlns['abc']
)
) {
continue;
}
while ($reader->localName === 'ABCRecord') {
if ($reader->namespaceURI === 'http://www.abc-example.com') {
$node = $reader->expand($dom);
fputcsv(
$output,
[
$xpath->evaluate('string(abc:ABC)', $node),
// How to fetch values of attribute 'type' and 'status'?
$xpath->evaluate('string(abc:Entity/abc:Name)', $node)
]
);
}
$reader->next('ABCRecord');
}
Output (csv):
5EXZX4LPK,Bornheim
5967007LI,"MOON BANK"
Desired Output:
5EXZX4LPK,Lorem,Lipsum,Bornheim
5967007LI,Dolor,Amet,"MOON BANK"
How can I accomplish this?