Rob
Rob

Reputation: 6380

Exporting posts for CSV file download

How can I incorporate my loop below to be exported as a CSV?

<?php $answers = new WP_Query(array('cat' => 25, 'order' => 'DESC')); ?>
<table width="100%" border="1" cellspacing="1" cellpadding="1">
      <tr>
        <td valign="top">Name</td>
        <td valign="top">Submission/production title</td>
        <td valign="top">Performance space</td> 
      </tr>
<?php if ($answers->have_posts()) : while ($answers->have_posts()) : $answers->the_post(); ?>   
      <tr>
        <td><?php echo the_title(); ?></td>
        <td><?php echo the_field('submit_submission_production_title'); ?></td>
        <td><?php echo the_field('submit_performance_space'); ?></td>  
      </tr>
   <?php endwhile; ?> 
    </table>                    
<?php endif; ?>

How can I integrate this with fputcsv?

<?php
$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
    fputcsv($fp, split(',', $line), ',', '&quot;');
}
fclose($fp);
?>

Upvotes: 0

Views: 375

Answers (1)

brasofilo
brasofilo

Reputation: 26075

First, the_title and the_field* are functions that do echo by themselves, you don't need echo the_title().

* Assuming that this is from Advanced Custom Fields.

Just build an array, like:

$answers = new WP_Query( array('cat' => 25, 'order' => 'DESC') ); 
if ( $answers->have_posts() ) {
    $list = array( 'Name,Submission/production title,Performance space' );
    while ( $answers->have_posts() ) {
        $title = get_the_title();
        $field1 = get_field('submit_submission_production_title');
        $field2 = get_field('submit_performance_space');
        $list[] = $title . ',' . $field1 . ',' . $field2;

        // IF ENCLOSING DOUBLE QUOTES ARE NEEDED
        // $list[] = '"' . $title . '","' . $field1 . '","' . $field2 . '"';
    }
}

Upvotes: 1

Related Questions