Comment un tableau peut-il être converti en fichier CSV ?
Un exemple de tableau est donné ci-dessous :
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 ) ) ) ) )
Pour convertir un tableau en fichier CSV, la fonction suivante peut être utilisé :
/** * 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 ); }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!