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;
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.
$headers = array('Foo', 'Bar', 'Baz');
$data = array(
array(1, 2, 3),
array(4, 5, 6)
);
$fh = fopen('php://output', 'w');
fputcsv($fh, $headers);
foreach ($data as $row) {
fputcsv($fh, $row);
}
That's how you use fputcsv
to output CSV data. The headers are simply like any other row, you just output them first. Your code makes absolutely no use of fputcsv
, you need to rewrite what you're doing there.
Your current code doesn't make any sense - you write to the file handle before you've opened it. You write to both the stdout and the file (which it turns out is also stdout) AND seem to be expecting the file to be included in the output. You send content to the browser before the headers without using output buffering.
(to answer your question, immediately before the foreach loop - but that's not going to fix the other problems)