Export custom post types as xml?

For a web page I’m working on I’ve created a plugin where user can put various members and their info in, and I’ve created a page template where I output these members out on a page.

This works out as it should, but I’d like to have a ‘download as xml’ button below this on the page.

Read More

So I’ve tried adding to my page template this

<div class="download_button">

    <?php

    $args = array(
        'post_type' => 'members',
        'posts_per_page' => -1,
        'order' => 'ASC',
        );

    $loop = new WP_Query( $args );

    $out_array = array();

    while ( $loop->have_posts() ) : $loop->the_post();
    $post_meta = get_post_meta($post->ID);

    $mail_array = explode(', ', $post_meta['Members_contact_mail'][0]);
    $email = array();
    if (is_array($mail_array)) {
        foreach ($mail_array as $key) {
            $email[] = $key;
        }
    }

    $phone_array = explode(', ', $post_meta['Members_contact_phone'][0]);
    $phone = array();
    if (is_array($phone_array)) {
        foreach ($phone_array as $key_phone) {
            $phone[] = $key_phone;
        }
    }

    $title = get_the_title();

    $out_array[] = array(
        $title,
        $post_meta['Members_address'][0],
        $post_meta['Members_person_in_charge'][0],
        $post_meta['Members_entry_date'][0],
        $phone,
        $email,
        $post_meta['Members_oib'][0]
        );

    endwhile;

    $phpexcel = new Excel_Xml;
    $phpexcel->addWorksheet('members', $out_array);
// $phpexcel->sendWorkbook('members.xls');

    ?>
    <a href="<?php echo esc_url( $phpexcel->getWorkbook() );?>" download=""><i class="bm-download"></i> <?php esc_html_e('members.xml', 'theme') ?></a>
</div>

In my page template I’ve included the file called excel_xml.php that I’ve got from here.

Now the thing that’s bothering me is how to create a working download link.

If I uncomment the

$phpexcel->sendWorkbook('members.xls');

In my download_button div I’ll actually get the xml file, so I can see that this works. But that’s not what I need. I’ve tried with other functions from excel_xml.php file, but none of those worked.

Does anyone have any experience with this?

SOLUTION:

This seems to work:

            $phpexcel = new Excel_Xml;
            $phpexcel->addWorksheet('members', $out_array);
            $phpexcel->writeWorkbook('members.xls');

            ?>
            <a class="member_download" href="<?php echo home_url(); ?>members.xls" target="_blank"><i class="bm-download"></i> <?php esc_html_e('members.xls', 'theme') ?></a>

The .xls file is saved to a root folder when you enter a page. When you click on the button it downloads the file.

Related posts