douyimin1083 2013-12-03 14:43
浏览 22
已采纳

通过PHP的CSV标头?

I have the following code to produce a CSV file from content in Wordpress but I need to add headers to the four columns that are produced. Where can I define these as they will always be fixed names?

$fileName = 'Optical_test_results.csv';
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");

$fh = @fopen( 'php://output', 'w' );
$arr_query_args = array(
    'numberposts'  => -1,
    'orderby'      => 'post_title',
    'post_type'    => 'page',
    'exclude'      => '24'
);

$arr_posts = get_posts( $arr_query_args );
global $post;

foreach( $arr_posts as $this_post ) { 
    $permalink = get_permalink($this_post->ID);
    $page_number = get_post_meta($this_post->ID, "part_number", true);
    $serial = $this_post->post_title;
    $s1 = get_post_meta($this_post->ID, 'tracking_number', true);
    $s2 = get_the_title($page_number);
    $s3 = $permalink;
    $results = $serial.','.$s1.','.$s2.','.$s3."
";
    echo $results;
    fputcsv($fh);
}


$headerDisplayed = false;
fclose($fh);

exit;
  • 写回答

3条回答 默认 最新

  • dqf2015 2013-12-03 14:51
    关注

    You can use fputcsv just like a data row. There is no difference in a header and data in csv.

    fputcsv($fh, array('header 1', 'header 2', 'header 3'));
    

    In your loop you are not using fputcsv correctly:

    $results = $serial.','.$s1.','.$s2.','.$s3."
    ";
    echo $results;
    fputcsv($fh);
    

    should be

    fputcsv($fh, array($serial, $s1, $s2, $s3));
    

    and you are opening the file after the loop has completed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的