将数组转换为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注释中的man条目之一的改编。而且您可能想要展平该数组;不知道如果您传递一个多维的行会发生什么。

/**

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

}

以上是 将数组转换为csv 的全部内容, 来源链接: utcz.com/qa/413270.html

回到顶部