Search code examples
phpdatabasewordpressexport-to-excel

How do I extract from WordPress database to MS Excel?


I am trying to add data into excel file which is extracted from wordpress database, Actually I am trying to export data (tags) from database into excel file. And I write down a code, but when I click on generate button. This generates empty file.

Please guys check what I am doing wrong.

Codes are below:

if (check_admin_referer('tag-export')) 
{
    $blogname = str_replace(" ", "", get_option('blogname'));
    $date = date("m-d-Y");
    $xls_file_name = $blogname."-exported-tags-".$date;

    $tags = get_terms( 'post_tag' , 'hide_empty=0' );
    $count = count($tags);

    if ( $count > 0 )
    {
        echo 'name' . "\t" . 'slug' . "\n";

        foreach ( $tags as $tag ) 
        {
            echo $tag->name . "\t" . $tag->slug . "\n";
        }
    }

    ob_clean();
    echo $xls_file;

    header( "Content-Type: application/vnd.ms-excel" );
    header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
    exit();
}

The above codes are not writing data into excel file. please check and let me know.


Solution

  • Just based on your existing code:

    if (check_admin_referer('tag-export')) 
    {
        $blogname = str_replace(" ", "", get_option('blogname'));
        $date = date("m-d-Y");
        $xls_file_name = $blogname."-exported-tags-".$date;
    
        $tags = get_terms( 'post_tag' , 'hide_empty=0' );
        $count = count($tags);
    
        $xls_file = '';
        if ( $count > 0 )
        {
            $xls_file .= 'name' . "\t" . 'slug' . "\n";
    
            foreach ( $tags as $tag ) 
            {
                $xls_file .= $tag->name . "\t" . $tag->slug . "\n";
            }
        }
    
        ob_clean();
        header( "Content-Type: application/vnd.ms-excel" );
        header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
    
        echo $xls_file;
    
        exit();
    }