0

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?

Philipp M
  • 3,306
  • 5
  • 36
  • 90
  • To get "lorem" en "dolor", you can add: `$xpath->evaluate('string(abc:Entity/@type)', $node)`. I trust you can add `status` yourself ? – Luuk Apr 22 '22 at 14:15
  • The question [Getting attribute using XPath](https://stackoverflow.com/questions/4531995/getting-attribute-using-xpath) was asked earlier, but not PHP specific. This does not really matter because XPath keeps XPath, and does not (or should not?) change because of PHP. – Luuk Apr 22 '22 at 14:24
  • Great, thanks a lot! – Philipp M Apr 22 '22 at 14:27

0 Answers0