i am trying to export csv using php/wordpress,I have following array inside while loop,Which is showing "name" of user
Array
(
[0] => Meck
)
Array
(
[0] => Bisk
)
...
And similarly i am getting email inside while loop
Array
(
[0] => mailto:[email protected]
)
Array
(
[0] => mailto:[email protected]
)
Now i want to export this data in csv,but data is showing in single column instead of seprate like this
Name Email
meck
mailto:[email protected]
bisk
mailto:[email protected]
Here is my current code
global $wpdb;
$filename = 'Student_Table_' . time() . '.csv';
$header_row = array(
'Name',
'Email',
);
$data_rows = array();
ob_end_clean ();
$fh = @fopen( 'php://output', 'w' );
header( "Content-Disposition: attachment; filename={$filename}" );
fputcsv( $fh, $header_row );
while ( $query->have_posts() ) : $query->the_post();
$email = get_post_meta( get_the_ID(), 'glow_user_email', true ); // contaning email of user
$user_lastname = get_post_meta( get_the_ID(), 'glow_user_lname', true );
$user_lastname_array = $array = explode(' ', $user_lastname); // contaning name of user
//trying to merge both arrays
$data = $user_lastname_array.",".$email;
fputcsv( $fh, $data );
endwhile;
My Answer:
data in single row in csv file.
Here is the code snippet:
php
$csv_output = fopen('php://output', 'w');
while ($row = mysqli_fetch_assoc($result)) {
$data = array(
$row['column1'],
$row['column2'],
$row['column3']
);
fputcsv($csv_output, $data);
}
fclose($csv_output);
To fix this issue, you can try adding a newline character after each row in the CSV file. Here is the updated code snippet:
php
$csv_output = fopen('php://output', 'w');
while ($row = mysqli_fetch_assoc($result)) {
$data = array(
$row['column1'],
$row['column2'],
$row['column3']
);
fputcsv($csv_output, $data);
fwrite($csv_output, "\n");
}
fclose($csv_output);
This should output each row of data on a new line in the CSV file.
Rate this post
4 of 5 based on 3360 votesComments