2010-10-14 102 views
36

如何將數組轉換爲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 
           ) 

         ) 

       ) 

     ) 

) 
+3

你可能想用標記任何語言的代碼寫在這個問題上這將幫助你在你的問題的方式更多的眼球。 :) – 2010-10-14 13:34:27

+2

我不認爲有一種方法可以在CSV中呈現多維度,是嗎? – Hannes 2010-10-14 13:38:50

+2

另請參閱[本解決方案](http://stackoverflow.com/a/13474770/57091),它將'fputcsv()'與'ob_start()一起使用; $ df = fopen(「php:// output」,'w'); FCLOSE($ DF);返回ob_get_clean();'。 – robsch 2015-10-08 06:15:51

回答

72

我用下面的函數,該函數;這是對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); 
} 
+1

嗨保羅,謝謝它真的幫了我很多。你是最好的! :D – rayss 2010-10-14 15:48:11

+0

嗨,這對我有用。但我有一個問題,我如何使它在1行後創建一個新行?我在for循環中添加了一個計數器,如果它的第一個索引結束,我會添加一個新行,如$ output [$ i]。=「\ r \ n」;它會創建一個新行,但它也會在下一行中添加一個新單元。 – user1149244 2013-07-03 07:43:47

+0

哇這太棒了! 謝謝! – 2014-12-20 08:28:10

14
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>' ; 
+0

嗨,Paulrajj,非常感謝。你真的幫助我的問題。你真棒的傢伙! :D – rayss 2010-10-14 15:47:42

41

我的解決方案需要陣列以不同的格式比問題提供:

<? 
    $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 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的代碼比我更聰明,所以我相信我不是原作者。不幸的是,我已經失去了我所掌握的地方,所以我不能把它歸功於誰。

15

輕微適應上述的解決由kingjeffrey當你想創建和模板內回聲CSV(即 - 大多數框架將啓用輸出緩衝,你需要設置頁眉等在控制器)

// 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以及這個blog post,我發現了關於創建文本流的信息。

+3

此解決方案在不允許文件創建權限的情況下非常有用 – DKG 2013-06-25 10:07:55

-2

嗯,也許有點晚了4年後哈哈......但我一直在尋找的解決方案做對象CSV,但是這裏大多數解決方案實際上是一個數組CSV ...

一些修修補補後,在這裏是我的解決方案,將對象轉換爲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