<p><img src="https://img.php.cn/upload/article/000/887/227/169364887365792.jpg" alt="Data export: customized database table"></p>
<p>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. </p>
<p> Let us consider two situations: </p>
<ol>
<li>Custom tables reference native WordPress tables</li>
<li>Custom tables are completely independent from native tables</li>
</ol>
<p>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. </p>
<p>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. <em>Unfortunately</em>, 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. </p>
<p>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). </p>
<hr>
<h2>Determine the format</h2>
<p>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. </p>
<hr>
<h2>Price increase</h2>
<p>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. </p>
<p>First let us look at the structure of the class and then fill in the details of its methods. </p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">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();
</pre><div class="contentsignin">Copy after login</div></div>
<p><code>WPTuts_Log_Export_Admin_Page::load()</code> Initialize the class and hook callbacks to the appropriate operations: </p>
<ul>
<li>
<code>add_submenu</code> – Method responsible for adding pages under the "Tools" menu. </li>
<li>
<code>maybe_download</code> – This method will listen to check whether the download request has been submitted. This will also check permissions and nonce. </li>
</ul>
<p> 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 <code>init</code>, but since we only allow export files to be downloaded in admin, <code>admin_init</code> is more appropriate here. </p>
<p>Adding pages to your menu is easy. To add a page under Tools, we simply call <code>add_management_page()</code>. </p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">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') );
}
</pre><div class="contentsignin">Copy after login</div></div>
<p>Here <code>$hook_suffix</code> 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. </p>
<p> Above we set the method <code>display()</code> as the callback of our page, then we define it: </p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">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
}
</pre><div class="contentsignin">Copy after login</div></div>
<p>Finally, we hope to monitor when the above form is submitted and trigger the export file download. </p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">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();
}
</pre><div class="contentsignin">Copy after login</div></div>
<p>All that's left is to create the function <code>wptuts_export_logs()</code> to create and return our .xml file. </p>
<hr>
<h2>Create export file</h2>
<p>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 <code>text/xml</code> and the Content-Description to <code>File Transfer</code>. 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. </p>
<p> 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 <code>$args</code> array, as this is done by <code> Processed by wptuts_get_logs()</code>. </p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">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 */
}
</pre><div class="contentsignin">Copy after login</div></div>
<p>您会注意到,我们已将实际查询数组作为参数传递给 <code>wptuts_export_logs()</code> 函数。我们可以对此进行硬编码,但不这样做也是有道理的。虽然这里的目的只是导出表中的<em>所有内容</em>,但将查询作为参数传递允许我们稍后添加在特定时间范围内或针对特定用户导出日志的选项。</ p>
<p>创建 XML 文件时,我们需要确保标签之间打印的值不包含字符 <code>&</code>、<code><</code> 或 <code>></code>。为了确保这一点,对于 ID,我们使用 <code>absint</code> 清理数据,并使用 <code>sanitize_key</code> 清理对象类型和活动(因为我们希望这些仅包含小写字母数字、下划线和连字符)。</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">/* Print logs to file */
echo '<logs>';
foreach ( $logs as $log ) { ?>
<item>
<log_id><?php echo absint($log->log_id); ?></log_id>
<activity_date><?php echo mysql2date( 'Y-m-d H:i:s', $log->activity_date, false ); ?></activity_date>
<user_id><?php echo absint($log->user_id); ?></user_id>
<object_id><?php echo absint($log->object_id); ?></object_id>
<object_type><?php echo sanitize_key($log->object_type); ?></object_type>
<activity><?php echo sanitize_key($log->activity); ?></activity>
</item>
<?php }
echo '</logs>';
</pre><div class="contentsignin">Copy after login</div></div>
<p>更一般地,您可以使用以下函数将要打印的值包装在 <code>CDATA</code> 标记内来清理它们:</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;">/**
* 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 '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $string ) . ']]>';
}
</pre><div class="contentsignin">Copy after login</div></div>
<p>最后我们 <code>exit()</code> 以防止任何进一步的处理:</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbal:false;"> /* Finished - now exit */
exit();
</pre><div class="contentsignin">Copy after login</div></div>
<p>导航到我们的导出页面,单击“下载活动日志”应提示下载 XML 文件。</p>
<hr>
<h2>摘要</h2>
<p>在本教程中,我们研究了从自定义表中导出数据。不幸的是,当数据引用本机 WordPress 表时,这充其量是有问题的。上述方法仅适用于数据无法做到这一点的情况。使用的示例(我们的活动日志)显然不属于此类,只是为了与本系列的其余部分保持一致而使用。</p>
<p>当数据<em>确实</em>引用本机表时,显然有必要将其与本机表一起导入,并在此过程中跟踪导入期间发生的 ID 任何更改。目前,现有的导入和导出处理程序无法实现这一点,因此唯一可行的选择是创建自己的处理程序。在自定义数据仅引用单个帖子类型的简单情况下,可以设计导入和导出处理程序来处理该帖子类型以及自定义数据,并通知用户不要使用该帖子类型的本机导出器。
</p>
<p>在本系列的下一部分中,我们将为导出的 .xml 文件创建一个简单的导入处理程序。</p>
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!