2015-04-23 134 views
7

我在我的插件页面中使用了一个简单的数组到CSV导出功能来生成报表。Array-to-CSV导出功能在WordPress插件中遇到问题

当我运行此代码时,我收到一个错误消息,它将导出整个html内容以及我的预期数组。

这里是我的代码:

function convert_to_csv($input_array, $output_file_name, $delimiter) 
{ 
    clearstatcache(); 
    /** open raw memory as file, no need for temp files */ 
    $temp_memory = fopen('php://memory', 'w'); 
    /** loop through array */ 



    foreach ($input_array as $line) { 
     /** default php csv handler **/ 
     fputcsv($temp_memory, $line, $delimiter); 
    } 

    //echo '<pre>'; 
    //print_r($temp_memory); exit; 
    /** rewrind the "file" with the csv lines **/ 
    fseek($temp_memory, 0); 
    /** modify header to be downloadable csv file **/ 
    header('Content-Type: application/csv'); 
    header('Content-Disposition: attachement; filename="' . $output_file_name . '";'); 
    /** Send file to browser for download */ 
    fpassthru($temp_memory); 
} 

/** Array to convert to csv */ 

$array_to_csv = Array(
    Array(12566, 
     'Enmanuel', 
     'Corvo' 
    ), 
    Array(56544, 
     'John', 
     'Doe' 
    ), 
    Array(78550, 
     'Mark', 
     'Smith' 
    ) 

); 

clearstatcache(); 

convert_to_csv($array_to_csv, 'report.csv', ','); 
+0

我在运行此代码时没有收到错误消息。我按预期下载了csv。 – Rasclatt

+0

当我在WordPress的插件环境中运行此代码时,我得到的csv显示列表中的所有html代码 –

+0

代码按预期运行,并下载了csv文件。添加关于插件和Wordpress版本的信息,以帮助我们了解这一点。 – geeves

回答

0

我猜,WP是其正常运作执行后调用这个函数,所以你会得到CSV后的HTML模板输出。在fpassthru之后加入exit声明应该这样做,但是您需要注意,这不会影响Wordpress在每个页面响应结束时执行的其他操作。例如Drupal为此仅有一个drupal_exit()函数。我对WP的知识不够熟悉,但wp_die() function的文档建议您可以使用PHP exit而没有太多问题