I was working on creating a small code that would help me export any array into a CSV file.

I have created the small code and this helped me quite much:

$filename="mycsvfilename";
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=".$name.".csv");
foreach($data as $value) {
    fputcsv($output, $value);
}
fclose($output) or die("Can't close php://output");

The array from $data si added into the csv one row at a time. My full export PHP WordPress file was this:

$args = array(
    'posts_per_page' => -1,
    'post_status'=>'publish',
    'post_type'=>"leads");
$post = query_posts($args);
$data[] = array("First name","Last Name","Job title","Company/Brokerage","Years in the real estate field", "Highest level of education","Affiliated with any real estate organizations?","Email","Primary state licensed","Mobile phone","Company phone");
$filename = "leads";
foreach($post As $key => $value){
    $meta = get_post_meta($value->ID);
    $data[] = array($meta['firstname'][0],$meta['lastname'][0],$meta['jobtitle'][0],$meta['company'][0],$meta['years'][0],$meta['education'][0],$meta['affil'][0],$meta['email'][0],$meta['state'][0],$meta['mobile'][0],$meta['mobilecom'][0]);
}
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=".$filename.".csv");
foreach($data as $value) {
    fputcsv($output, $value);
}
fclose($output) or die("Can't close php://output");

The code above this is just exporting custom fields to a CSV file.

You might find interesting:   How to Stop Search Engines from Crawling a WordPress Site

LEAVE A REPLY

Please enter your comment!
Please enter your name here