Skip to content

Instantly share code, notes, and snippets.

@mariovalney
Created December 4, 2019 17:29
Show Gist options
  • Save mariovalney/b7500e0fec072dc39b100efb26fd3a36 to your computer and use it in GitHub Desktop.
Save mariovalney/b7500e0fec072dc39b100efb26fd3a36 to your computer and use it in GitHub Desktop.
Turn exported WooCommerce/WordPress Orders into CSV file
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
// Load file
$xml_string = file_get_contents(dirname(__FILE__) . '/file.xml');
str_replace($xml_string, 'dc:', 'dc-');
str_replace($xml_string, 'wp:', 'wp-');
str_replace($xml_string, 'content:', 'content-');
str_replace($xml_string, 'excerpt:', 'excerpt-');
// Turn into array
$xml = simplexml_load_string($xml_string, null, LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
// Header
$output = fopen("php://output", "wb");
fputcsv($output, ['Order', 'Status', 'User', 'Billing Name', 'Billing Last Name', 'Billing Mail', 'Billing Phone', 'Billing Cellphone', 'Message / Excerpt', 'Total of Order']);
// Function makes life easy
function print_post_meta($item, $meta) {
foreach ($item['wp-postmeta'] as $value) {
if ($value['wp-meta_key'] === $meta) {
return $value['wp-meta_value'] ?: '';
}
}
return '';
}
// Parse Posts
foreach ($array['channel']['item'] as $item) {
if ($item['wp-post_type'] !== 'shop_order') {
continue;
}
$row = [];
$row[] = ($item["wp-post_id"] ?: '');
$row[] = ($item["wp-status"] ?: '');
$row[] = print_post_meta($item, '_customer_user');
$row[] = print_post_meta($item, '_billing_first_name');
$row[] = print_post_meta($item, '_billing_last_name');
$row[] = print_post_meta($item, '_billing_email');
$row[] = print_post_meta($item, '_billing_phone');
$row[] = print_post_meta($item, '_billing_cellphone');
$row[] = ($item["excerpt-encoded"] ?: '');
$row[] = print_post_meta($item, '_order_total');
fputcsv($output, $row);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment