How to convert an array into a CSV file?
This is my array:
stdClass Object
(
[OrderList_RetrieveByContactResult] => stdClass Object
(
[OrderDetails] => stdClass Object
(
[entityId] => 1025298
[orderId] => 10952
[orderName] => testing
[statusTypeId] => 4652
[countryCode] => AU
[orderType] => 1
[invoiceNumber] => 0
[invoiceDate] => 0001-01-01T00:00:00
[userID_AssignedTo] => 11711
[shippingAmount] => 8.95
[shippingTaxRate] => 0
[shippingAttention] =>
[shippingInstructions] =>
[shippingOptionId] => 50161
[discountCodeId] => 0
[discountRate] => 0
[totalOrderAmount] => 408.45
[directDebitTypeId] => 0
[directDebitDays] => 0
[isRecur] =>
[nextInvoiceDate] => 0001-01-01T00:00:00
[endRecurDate] => 0001-01-01T00:00:00
[cycleTypeID] => 1
[createDate] => 2010-10-08T18:40:00
[lastUpdateDate] => 2010-10-08T18:40:00
[deleted] =>
[products] => stdClass Object
(
[Product] => stdClass Object
(
[productId] => 674975
[productCode] =>
[productDescription] =>
[units] => 10
[unitPrice] => 39.95
[unitTaxRate] => 0
[totalProductPrice] => 399.5
[productName] => Acne Clearing Gel
)
)
[addresses] => stdClass Object
(
[Address] => stdClass Object
(
[addressTypeID] => 8
[addressLine1] => Cebu City
[city] => Cebu
[zipcode] => 6000
[state] =>
[countryCode] => PH
)
)
)
)
)
My solution requires the array be formatted differently than provided in the question:
We define our function:
Then we output our data as a CSV:
I have used this with several projects, and it works well. I should note that the
outputCSV
code is more clever than I am, so I am sure I am not the original author. Unfortunately I have lost track of where I got it, so I can't give the credit to whom it is due.Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
Note that for the
$key => $value
to work, yourobject
's attributes must be public, the private ones will not get fetched.The end result is that you get something like this:
I'm using the following function for that; it's an adaptation from one of the man entries in the fputscsv comments. And you'll probably want to flatten that array; not sure what happens if you pass in a multi-dimensional one.
A slight adaptation to the solution above by kingjeffrey for when you want to create and echo the CSV within a template (Ie - most frameworks will have output buffering enabled and you are required to set headers etc in controllers.)
Credit to Kingjeffrey above and also to this blog post where I found the information about creating text streams.