I am trying to add all new WooCommerce orders to a CSV called orders.csv. All works great but cant get each order to be on a new line. It merges with header, ie Products12345. Any ideas why this could be happening? I’ve tried using /n and PHP_EOL.
add_action('woocommerce_checkout_order_processed', 'ppd_append_order_to_csv_full', 10, 1);
function ppd_append_order_to_csv_full($order_id) {
if (!$order_id) return;
$order = wc_get_order($order_id);
if (!$order) return;
$folder_path = ABSPATH . 'ppd/';
$csv_path = $folder_path . 'orders.csv';
if (!file_exists($folder_path)) {
mkdir($folder_path, 0755, true);
}
$need_headers = !file_exists($csv_path) || filesize($csv_path) === 0;
if ($need_headers) {
$file = fopen($csv_path, 'wb');
fwrite($file, "xEFxBBxBF"); // UTF-8 BOM for Excel
fputcsv($file, [
'Order ID',
'Shipping Method',
'Products'
]);
fwrite($file, PHP_EOL);
} else {
$file = fopen($csv_path, 'ab');
}
// Products
$items = [];
foreach ($order->get_items('line_item') as $item_id => $item) {
$product = $item->get_product();
$name = $item->get_name();
$sku = $product ? $product->get_sku() : '';
$qty = $item->get_quantity();
$unit_price = $qty > 0 ? number_format($item->get_total() / $qty, 2, '.', '') : '0.00';
$items[] = "{$name} (SKU: {$sku}) x {$qty} - £{$unit_price}";
}
$shipping_method_names = [];
foreach ($order->get_shipping_methods() as $shipping_item) {
$shipping_method_names[] = $shipping_item->get_method_title();
}
$formatted_phone = $order->get_billing_phone() ? "'" . $order->get_billing_phone() : '';
// Row data
$data = [
$order->get_id(),
implode(' | ', $shipping_method_names),
implode(' | ', $items) // <- this often has commas
];
fputcsv($file, $data);
fwrite($file, PHP_EOL);
fclose($file);
}