将数组转换成csv

如何将数组转换为CSV文件?

这是我的数组:

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 ) ) ) ) ) 

我正在使用下面的函数; 这是对fputscsv评论中的一个人的改编。 而且你可能想把这个数组弄平。 不知道如果你通过一个多维的会发生什么事情。

 /** * 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 ); } 

我的解决scheme要求数组的格式不同于问题中提供的格式:

 <? $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' ), ); ?> 

我们定义我们的function:

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

然后我们输出我们的数据为CSV:

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

我已经用了几个项目,它运作良好。 我应该注意到输出的outputCSV代码比我更聪明,所以我相信我不是原作者。 不幸的是,我忘记了自己在哪里,所以我不能把它归功于谁。

当你想要在模板中创build和回显CSV时,对kingjeffrey的解决scheme稍作调整(即,大多数框架将启用输出缓冲,并且需要在控制器中设置标题等)。

 // Create Some data <?php $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' ), ); // Create a stream opening it with read / write mode $stream = fopen('data://text/plain,' . "", 'w+'); // Iterate over the data, writting each line to the text stream foreach ($data as $val) { fputcsv($stream, $val); } // Rewind the stream rewind($stream); // You can now echo it's content echo stream_get_contents($stream); // Close the stream fclose($stream); 

感谢上面的Kingjeffrey,还有这个博客文章 ,我发现了关于创build文本stream的信息。

 function array_2_csv($array) { $csv = array(); foreach ($array as $item) { if (is_array($item)) { $csv[] = array_2_csv($item); } else { $csv[] = $item; } } return implode(',', $csv); } $csv_data = array_2_csv($array); echo "<pre>"; print_r($csv_data); echo '</pre>' ; 

也许有点晚,4年后哈哈…但我正在寻找解决scheme做CSV对象,但是这里的大多数解决scheme实际上是arrays到CSV …

经过一番修改,这里是我的解决scheme,将对象转换为CSV,我觉得很整齐。 希望这会帮助别人。

 $resp = array(); foreach ($entries as $entry) { $row = array(); foreach ($entry as $key => $value) { array_push($row, $value); } array_push($resp, implode(',', $row)); } echo implode(PHP_EOL, $resp); 

请注意,要使$key => $value起作用,您的object的属性必须是公有的,私有的不会被获取。

最终的结果是你得到这样的东西:

 blah,blah,blah blah,blah,blah