Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array into csv

Tags:

arrays

php

csv

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                                 )                          )                  )          )  ) 
like image 758
rayss Avatar asked Oct 14 '10 13:10

rayss


People also ask

How will you save an array of numbers in CSV format?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

How do I convert a NumPy array to CSV?

Use the numpy. savetxt() Function to Save a NumPy Array in a CSV File. The savetxt() function from the numpy module can save an array to a text file. We can specify the file format, delimiter character, and many other arguments to get the final result in our desired format.

How do I create a CSV File from a list in Python?

The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.


2 Answers

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.

/**   * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.   * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120   */ function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {     $delimiter_esc = preg_quote($delimiter, '/');     $enclosure_esc = preg_quote($enclosure, '/');      $output = array();     foreach ( $fields as $field ) {         if ($field === null && $nullToMysqlNull) {             $output[] = 'NULL';             continue;         }          // Enclose fields containing $delimiter, $enclosure or whitespace         if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {             $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;         }         else {             $output[] = $field;         }     }      return implode( $delimiter, $output ); } 
like image 111
Paul Avatar answered Sep 23 '22 13:09

Paul


My solution requires the array be formatted differently than provided in the question:

<?     $data = array(         array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),         array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),         array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),     ); ?> 

We define our function:

<?     function outputCSV($data) {         $outputBuffer = fopen("php://output", 'w');         foreach($data as $val) {             fputcsv($outputBuffer, $val);         }         fclose($outputBuffer);     } ?> 

Then we output our data as a CSV:

<?     $filename = "example";      header("Content-type: text/csv");     header("Content-Disposition: attachment; filename={$filename}.csv");     header("Pragma: no-cache");     header("Expires: 0");      outputCSV($data); ?> 

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.

like image 45
kingjeffrey Avatar answered Sep 21 '22 13:09

kingjeffrey