如何將陣列轉換為 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 ) ) ) ) )
要將陣列轉換為CSV文件,可以使用下列函數:
/** * 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 ); }
以上是如何有效地將 PHP 陣列轉換為 CSV 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!