XML to CSV with PHP converter [problem with images grabing]



PHP Snippet 1:

$filexml = 'imp2.xml';

if (file_exists($filexml))  {
    // Only open file once you know it exists
    $xml = simplexml_load_file($filexml);
    $i = 1;           // Position counter
    $values = [];     // PHP array

    // Writing column headers
    $columns = array('id', 'barcode', 'title', 'description', 'price', 'sec_costs', 'quantity', 'warranty', 'weight', 'delivery_text', 'manufacturer', 'image', 'product_with_gift', 'barcode_format');

    // Open output file at start
    $fs = fopen('csv.csv', 'w');
    fputcsv($fs, $columns);

    // Iterate through each <product> node
    $node = $xml->xpath('//product');

    foreach ($node as $n) {
        // Iterate through each child of <item> node
        foreach ($columns as $col) {
            // Use //'.$col so node doesn't have to be directly under product
            $dataMatch = $xml->xpath('//product['.$i.']//'.$col);
            if (count($dataMatch) > 0) {
                // Build list of all matches
                $newData = '';
                foreach ( $dataMatch as $data)  {
                    $newData .= trim((string)$data).",";
                }
                // Remove last comma before adding it in
                $values[] = rtrim($newData, ",");
            } else {
                $values[] = '';
            }
        }
        fputcsv($fs, $values);

        $values = [];    // Clean out array for next <item> (i.e., row)
        $i++;            // Move to next <item> (i.e., node position)
    }
    // Close file only at end
    fclose($fs);
}