Convert Array into CSV for Order Data Export
Converting a complex nested PHP array structure into a CSV file is a common requirement when building reporting tools or preparing data for external systems like Excel or Google Sheets. The source data provided demonstrates a typical e-commerce order payload: it contains top-level identifiers, shipping details, calculated totals, and nested collections for products and addresses.
The challenge isn't just writing the rows; it's handling the structure. Your data is wrapped in a stdClass object with a deeply nested hierarchy (OrderList_RetrieveByContactResult -> OrderDetails). To generate a flat CSV, you must traverse this tree, flatten the nested objects into single rows, and normalize the column names so they align logically.
Flattening Nested Structures
The most critical step is mapping your object properties to specific CSV columns. If you simply dump the entire stdClass object using fputcsv, it will fail because fputcsv expects a simple array where keys represent columns and values represent cells. It cannot handle nested objects directly.
You need to recursively traverse the data or manually flatten the specific sections relevant to your report. For the example provided, you would likely want columns like Order ID, Customer Name, Total Amount, and then sub-columns for line items such as Product Code and Unit Price.
Here is a practical approach using PHP to map the nested stdClass data into a flat associative array:
function flattenOrderData($orderDetails) {
$flatRow = [];
// Map top-level order details
$flatRow['Order ID'] = $orderDetails->orderId;
$flatRow['Status Type ID'] = $orderDetails->statusTypeId;
$flatRow['Country Code'] = $orderDetails->countryCode;
$flatRow['Total Amount'] = $orderDetails->totalOrderAmount;
$flatRow['Shipping Amount'] = $orderDetails->shippingAmount;
// Handle nested products
if (isset($orderDetails->products) && isset($orderDetails->products->Product)) {
$product = $orderDetails->products->Product;
$flatRow['Product Code'] = $product->productCode ?? '';
$flatRow['Product Description'] = $product->productDescription ?? '';
$flatRow['Units'] = $product->units;
$flatRow['Unit Price'] = $product->unitPrice;
$flatRow['Total Product Price'] = $product->totalProductPrice;
$flatRow['Product Name'] = $product->productName;
}
// Handle nested addresses
if (isset($orderDetails->addresses) && isset($orderDetails->addresses->Address)) {
$addr = $orderDetails->addresses->Address;
$flatRow['City'] = $addr->city;
$flatRow['Zipcode'] = $addr->zipcode;
$flatRow['Country Code'] = $addr->countryCode; // Note: potential duplicate key handling needed
}
return $flatRow;
}
In this example, we explicitly map keys. Notice how we handle empty strings or missing values using the null coalescing operator (??). The source data shows several fields like shippingAttention or productCode are empty in the sample object. If you don't sanitize these before writing to CSV, your file might contain literal "NULL" strings or formatting errors depending on how the consumer reads it.
Writing to File with fputcsv
Once you have your data transformed into an array of associative arrays (where each inner array is one row), fputcsv becomes the standard tool. It writes directly to a file handle, which is efficient for large datasets compared to building a massive string in memory first.
$outputFile = 'orders_export.csv';
$handle = fopen($outputFile, 'w');
// Define headers based on your mapped keys
$headers = array_keys($flatRow);
fputcsv($handle, $headers);
foreach ($orderList as $order) {
$flat = flattenOrderData($order['OrderDetails']);
// Handle duplicate column names (e.g., Country Code in Order and Address)
if (!empty($flat['Order Country'])) {
$flat['Address Country'] = $flat['Country Code'];
unset($flat['Country Code']);
}
fputcsv($handle, array_values($flat));
}
fclose($handle);
Handling Edge Cases and Pitfalls
The source material highlights several specific data quality issues you must address:
- Empty Strings vs. NULL: The example shows fields like
shippingAttentionas empty strings (""). When writing to CSV, an empty string is often acceptable, but some parsers treat it differently than a missing key. Ensure your mapping logic explicitly converts undefined properties to empty strings if necessary. - Duplicate Column Names: In the sample object,
countryCodeexists at the top level and inside theaddressessection. If you flatten this naively, both will map to the same column header, overwriting data. You must either rename keys (e.g.,OrderCountry,AddressCountry) or create separate columns for logical grouping. - Date Formats: Fields like
invoiceDate(0001-01-01T00:00:00) indicate invalid dates in the source data. Before exporting, validate these timestamps. Writing a Unix epoch or a placeholder like "Invalid Date" prevents Excel from misinterpreting them as extremely large numbers representing years far in the past.
Conclusion
Converting complex nested arrays to CSV requires manual mapping and careful handling of edge cases like empty fields and duplicate keys. By flattening your data structure first and then using fputcsv, you ensure a clean, readable output file that accurately represents the order details from your source object.
