Home  >  Article  >  Backend Development  >  Data export: customized database table

Data export: customized database table

WBOY
WBOYOriginal
2023-09-02 18:01:07756browse

Data export: customized database table

As mentioned in the first article in this series, one of the main problems with custom database tables is that they are not handled by existing import and export handlers. This article aims to address this problem, but it should be noted that there is currently no fully satisfactory solution.

Let us consider two situations:

  1. Custom tables reference native WordPress tables
  2. Custom tables are completely independent from native tables

The "worst case scenario" is the first scenario. Take a custom table that saves user activity logs as an example. It references the user ID, object ID, and object type - all of which reference data stored in native WordPress tables. Now imagine that someone wants to import all the data from their WordPress website into a second website. For example, it's entirely possible that when importing a post, WordPress has to assign it a new ID because a post with that ID might already exist in the second site.

In this case, it is necessary to track such changes and update the IDs referenced in the table. This in itself is not that difficult. Unfortunately, the WordPress Importer plugin for handling importing data from other WordPress sites lacks the necessary hooks to achieve this. As suggested in this comment, a potential workaround would be to store the data in metadata as well. Unfortunately, this results in duplicate data and violates database normalization—generally not a good idea. In the end, it's only really feasible in a few use cases.

The second case avoids this complexity, but still requires custom import and export handlers. We will demonstrate this situation in the next two articles. However, to be consistent with the rest of this series, we will stick with the activity log table, even though it is an example of case (1).


Determine the format

First we need to decide the format of the exported file. The best format depends on the nature (or "structure") of the data and how it will be used. In my opinion, XML is generally better because it can handle one-to-many relationships. However, sometimes if the data is in tabular form, CSV may be preferable, especially because of its ease of integration with spreadsheet applications. In this example we will use XML.


Price increase

The next step is to create an admin page to allow users to export data from the log table. We will create a class that will add a page below the Tools menu item. The page only contains a button prompting the user to download the export file. The class will also add a handler to listen for form submissions and trigger file downloads.

First let us look at the structure of the class and then fill in the details of its methods.

class WPTuts_Log_Export_Admin_Page{

    /**
     * The page hook suffix
     */
    static $hook_suffix='';

    static function load(){
        add_action('admin_menu', array(__CLASS__,'add_submenu'));
        add_action('admin_init', array(__CLASS__,'maybe_download'));
    }

    static function add_submenu(){}

    static function maybe_download(){}

    static function display(){}
}
WPTuts_Log_Export_Admin_Page::load();

WPTuts_Log_Export_Admin_Page::load() Initialize the class and hook callbacks to the appropriate operations:

  • add_submenu – Method responsible for adding pages under the "Tools" menu.
  • maybe_download – This method will listen to check whether the download request has been submitted. This will also check permissions and nonce.

The export listener needs to be called early before any headers are sent, since we will be setting these headers ourselves. We could hook it to init, but since we only allow export files to be downloaded in admin, admin_init is more appropriate here.

Adding pages to your menu is easy. To add a page under Tools, we simply call add_management_page().

static function add_submenu(){
    self::$hook_suffix = add_management_page( __('Export Logs','wptuts-log'), __('Export Logs','wptuts-log'), 'manage_options', 'wptuts-export', array(__CLASS__,'display') );
}

Here $hook_suffix is a suffix used for various screen-specific hooks, discussed here. We don't use it here - but if you do, it's better to store its value in a variable rather than hardcoding it.

Above we set the method display() as the callback of our page, then we define it:

static function display(){

    echo '<div class="wrap">';
        screen_icon();
        echo '<h2>' . __( 'Export Activity Logs', 'wptuts-log' ) . '</h2>';
        ?>

        <form id="wptuts-export-log-form" method="post" action="">
            <p>
                <label><?php _e( 'Click to export the activity logs','wptuts-log' ); ?></label>
                <input type="hidden" name="action" value="export-logs" />
            </p>
            <?php wp_nonce_field('wptuts-export-logs','_wplnonce') ;?>
            <?php submit_button( __('Download Activity Logs','wptuts-log'), 'button' ); ?>
        </form>

    <?php
}

Finally, we hope to monitor when the above form is submitted and trigger the export file download.

static function maybe_download(){
     /* Listen for form submission */
    if( empty($_POST['action']) || 'export-logs' !== $_POST['action'] )
        return;

    /* Check permissions and nonces */
    if( !current_user_can('manage_options') )
        wp_die('');

    check_admin_referer( 'wptuts-export-logs','_wplnonce');

    /* Trigger download */
    wptuts_export_logs();
}

All that's left is to create the function wptuts_export_logs() to create and return our .xml file.


Create export file

The first thing we want the function to do is retrieve the log. If any, we need to set the appropriate headers and print them in XML format. Since we want the user to download the XML file, we set the Content-Type to text/xml and the Content-Description to File Transfer. We will also generate a suitable name for the downloaded file. Finally, we'll add some comments - these are completely optional, but helpful in guiding the user on what to do with the downloaded file.

Since we created the API for the table in the previous part of this series, our export handler does not need to touch the database directly - nor does it need to clean up the $args array, as this is done by Processed by wptuts_get_logs().

function wptuts_export_logs( $args = array() ) {

    /* Query logs */
    $logs = wptuts_get_logs($args);

    /* If there are no logs - abort */
    if( !$logs )
        return false;

    /* Create a file name */
    $sitename = sanitize_key( get_bloginfo( 'name' ) );
    if ( ! empty($sitename) ) $sitename .= '.';
    $filename = $sitename . 'wptuts-logs.' . date( 'Y-m-d' ) . '.xml';

    /* Print header */
    header( 'Content-Description: File Transfer' );
    header( 'Content-Disposition: attachment; filename=' . $filename );
    header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );

    /* Print comments */
    echo "<!-- This is a export of the wptuts log table -->\n";
    echo "<!-- (Demonstration purposes only) -->\n";
    echo "<!--  (Optional) Included import steps here... -->\n";

    /* Print the logs */
}

您会注意到,我们已将实际查询数组作为参数传递给 wptuts_export_logs() 函数。我们可以对此进行硬编码,但不这样做也是有道理的。虽然这里的目的只是导出表中的所有内容,但将查询作为参数传递允许我们稍后添加在特定时间范围内或针对特定用户导出日志的选项。 p>

创建 XML 文件时,我们需要确保标签之间打印的值不包含字符 & 或 <code>>。为了确保这一点,对于 ID,我们使用 absint 清理数据,并使用 sanitize_key 清理对象类型和活动(因为我们希望这些仅包含小写字母数字、下划线和连字符)。

/* Print logs to file */
echo '&lt;logs&gt;';
foreach ( $logs as $log ) { ?&gt;
    &lt;item&gt;
        &lt;log_id&gt;&lt;?php echo absint($log-&gt;log_id); ?&gt;&lt;/log_id&gt;
        &lt;activity_date&gt;&lt;?php echo mysql2date( 'Y-m-d H:i:s', $log-&gt;activity_date, false ); ?&gt;&lt;/activity_date&gt;
        &lt;user_id&gt;&lt;?php echo absint($log-&gt;user_id); ?&gt;&lt;/user_id&gt;
        &lt;object_id&gt;&lt;?php echo absint($log-&gt;object_id); ?&gt;&lt;/object_id&gt;
        &lt;object_type&gt;&lt;?php echo sanitize_key($log-&gt;object_type); ?&gt;&lt;/object_type&gt;
        &lt;activity&gt;&lt;?php echo sanitize_key($log-&gt;activity); ?&gt;&lt;/activity&gt;
    &lt;/item&gt;
&lt;?php }
echo '&lt;/logs&gt;';

更一般地,您可以使用以下函数将要打印的值包装在 CDATA 标记内来清理它们:

/**
 * Wraps the passed string in a XML CDATA tag.
 *
 * @param string $string String to wrap in a XML CDATA tag.
 * @return string
 */
function wptuts_wrap_cdata( $string ) {
    if ( seems_utf8( $string ) == false )
        $string = utf8_encode( $string );

    return '&lt;![CDATA[' . str_replace( ']]&gt;', ']]]]&gt;&lt;![CDATA[&gt;', $string ) . ']]&gt;';
}

最后我们 exit() 以防止任何进一步的处理:

    /* Finished - now exit */   
    exit();

导航到我们的导出页面,单击“下载活动日志”应提示下载 XML 文件。


摘要

在本教程中,我们研究了从自定义表中导出数据。不幸的是,当数据引用本机 WordPress 表时,这充其量是有问题的。上述方法仅适用于数据无法做到这一点的情况。使用的示例(我们的活动日志)显然不属于此类,只是为了与本系列的其余部分保持一致而使用。

当数据确实引用本机表时,显然有必要将其与本机表一起导入,并在此过程中跟踪导入期间发生的 ID 任何更改。目前,现有的导入和导出处理程序无法实现这一点,因此唯一可行的选择是创建自己的处理程序。在自定义数据仅引用单个帖子类型的简单情况下,可以设计导入和导出处理程序来处理该帖子类型以及自定义数据,并通知用户不要使用该帖子类型的本机导出器。

在本系列的下一部分中,我们将为导出的 .xml 文件创建一个简单的导入处理程序。

The above is the detailed content of Data export: customized database table. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn