Write CSV data using PHP

Write CSV data using PHP

Here is a little code snippet that illustrates how you can create a csv file using basic php. I'm leaving out some error checking that you would typically perform for before writing the file (checking for quotes, commas, etc.) but your specific needs will almost always be different that what I can attempt to code against, so I kept it simple and usable.

function write_csv() {
 
    //were we first write data to a multidimensional array
    $users = array(
                    array("Business1", "email1@yahoo.com", "user1", "address 1 city, state"),
                    array("Business2", "email2@yahoo.com", "user2", "address 2 city, state"),
                    array("Business3", "email3@yahoo.com", "user3", "address 3 city, state")
                );
 
    //we can optionally give each of these columns a heading
    array_unshift($users, array("Business Name", "Email", "Username", "Billing Address"));
 
    //next we create a file with php using <code>fopen</code>
    $file = fopen('users.csv', 'wb');
 
    //now we loop through each element in the array, adding our data for each item in the array
    foreach ($users as $user) {
        fputcsv($file, $user);
    }
 
    //be sure to close the output stream!
    fclose($file);
}
 
//create the file!
write_csv();

And that's it! This will create a file called users.csv in the executing directory, which is not necessarily where your php file lives. Next let's look at a more practical example. Say you have a WordPress website that you need some user data from. With a simple sql query we can generate a file that contains all of our users!

function write_csv_from_wp_data() {
    global $wpdb;
 
    //this time with a prepared statement by using wordpress's built in $wpdb class
    $users = $wpdb->get_results("SELECT `user_nicename`, `user_email`, `user_registered`, `user_url` FROM `yourWpDbPrefix_users` WHERE 1", ARRAY_A);
 
    array_unshift($users, array("User Name", "User Email", "Date Registered", "User Website"));
 
    $file = fopen('users.csv', 'wb');
 
    foreach ($users as $user) {
        fputcsv($file, $user);
    }
 
    fclose($file);
}
 
write_csv_from_wp_data();