在WordPress開發(fā)的過(guò)程中,我們經(jīng)常會(huì)遇到需要導(dǎo)出數(shù)據(jù)到XLS或CSV中,有一個(gè)比較強(qiáng)大的方法是使用PHPExcel類,強(qiáng)大往往意味著復(fù)雜。今天我們?yōu)榇蠹医榻B一種簡(jiǎn)單的導(dǎo)出數(shù)據(jù)到CSV中的方法。

純PHP導(dǎo)出數(shù)組為CSV的功能函數(shù)
函數(shù)中有3個(gè)參數(shù),需要轉(zhuǎn)化的數(shù)組,輸出的文件名,和數(shù)組值分隔符,一般為“,”
function wizhi_convert_to_csv($input_array, $output_file_name, $delimiter) {
/** 打開內(nèi)存為文件,這樣就不需要?jiǎng)?chuàng)建臨時(shí)文件了 */
$temp_memory = fopen('php://memory', 'w');
/** 遍歷數(shù)組 */
foreach ($input_array as $line) {
/** 默認(rèn) php csv 句柄 **/
fputcsv($temp_memory, $line, $delimiter);
}
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** 修改文件header為可下載的csv文件 **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** 發(fā)送文件到瀏覽器以便下載 */
fpassthru($temp_memory);
}
怎么使用純PHP導(dǎo)出數(shù)組為CSV的功能
$array_to_csv = Array(
Array(12566,
'Enmanuel',
'Corvo'
),
Array(56544,
'John',
'Doe'
),
Array(78550,
'Mark',
'Smith'
)
);
wizhi_convert_to_csv($array_to_csv, 'report.csv', ',');?
在WordPress中,把需要導(dǎo)出的數(shù)據(jù)轉(zhuǎn)換為數(shù)組,作為參數(shù)傳入到上面的函數(shù)中就可以了。怎么樣?是不是非常方便?


