PHP XML to CSV problem with minus values (fputcsv)

27 Views Asked by At

I have problem with my code:

<?php 
function readRowsFromSimpleXML(
  SimpleXMLElement $element, string $rowExpression, array $columnExpressions
): Generator {
    foreach ($element->xpath($rowExpression) as $rowNode) {
        $row = [];
        foreach ($columnExpressions as $column => $options) {
            if (is_array($options)) {
                [$expression, $callback] = $options;
            } else {
                $expression = $options;
                $callback = null;
            }
            $values = $rowNode->xpath($expression);
            if ($callback) {
                $row[$column] = $callback($values);
            } else {
                $row[$column] = (string)($rowNode->xpath($expression)[0] ?? '');
            }
        }
        yield $row;
    }
}

$rows = readRowsFromSimpleXML(
  simplexml_load_file('stock.xml'), 
  '//Item',
  $columns = [
      'ITEMNUMBER' => './ITEMNUMBER',
      'ITEMNAME' => './ITEMNAME',
      'COLOR' => './COLOR',
      'SIZE' => './SIZE',
      'BRAND' => './BRAND',
      'INVENTORY' => './INVENTORY',
      'SALESPRICE' => './SALESPRICE',
      'BARCODE' => './BARCODE'
  ]
);


$fh = fopen('stm.csv', 'w');
fputcsv($fh, array_keys($columns));
foreach ($rows as $row) {
    fputcsv($fh, array_values($row));
}
echo ('Export has been finished...');
 ?>

I would like to achieve that Inventory section will be always positive (sometimes XML file contain minuse values which should be converted to 0) does anyone knows how to change it? I was trying to use

if ($columns[6]<0)
    $columns[6] .= 0 ';'; 
else 
    $columns[6] .= trim($columns[6]) . ','; 

But without success.

0

There are 0 best solutions below