Table of Contents
Determine the format
Price increase
' . __( 'Export Activity Logs', 'wptuts-log' ) . '
Create export file
摘要
Home Backend Development PHP Tutorial Data export: customized database table

Data export: customized database table

Sep 02, 2023 pm 06:01 PM
Data output custom made Database Table

<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/169364887365792.jpg" class="lazy" 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 id="Determine-the-format">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 id="Price-increase">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;toolbar: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;toolbar: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;toolbar:false;'>static function display(){ echo '&lt;div class=&quot;wrap&quot;&gt;'; screen_icon(); echo '&lt;h2 id=&quot;Export-Activity-Logs-wptuts-log&quot;&gt;' . __( 'Export Activity Logs', 'wptuts-log' ) . '&lt;/h2&gt;'; ?&gt; &lt;form id=&quot;wptuts-export-log-form&quot; method=&quot;post&quot; action=&quot;&quot;&gt; &lt;p&gt; &lt;label&gt;&lt;?php _e( 'Click to export the activity logs','wptuts-log' ); ?&gt;&lt;/label&gt; &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;export-logs&quot; /&gt; &lt;/p&gt; &lt;?php wp_nonce_field('wptuts-export-logs','_wplnonce') ;?&gt; &lt;?php submit_button( __('Download Activity Logs','wptuts-log'), 'button' ); ?&gt; &lt;/form&gt; &lt;?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;toolbar: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 id="Create-export-file">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;toolbar: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 &quot;&lt;!-- This is a export of the wptuts log table --&gt;\n&quot;; echo &quot;&lt;!-- (Demonstration purposes only) --&gt;\n&quot;; echo &quot;&lt;!-- (Optional) Included import steps here... --&gt;\n&quot;; /* 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;toolbar:false;'>/* 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;'; </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;toolbar: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 '&lt;![CDATA[' . str_replace( ']]&gt;', ']]]]&gt;&lt;![CDATA[&gt;', $string ) . ']]&gt;'; } </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;toolbar:false;'> /* Finished - now exit */ exit(); </pre><div class="contentsignin">Copy after login</div></div> <p>导航到我们的导出页面,单击“下载活动日志”应提示下载 XML 文件。</p> <hr> <h2 id="摘要">摘要</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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ECharts and Java interface: how to export and share statistical chart data ECharts and Java interface: how to export and share statistical chart data Dec 17, 2023 am 08:44 AM

ECharts is a powerful, flexible and customizable open source chart library that can be used for data visualization and large-screen display. In the era of big data, the data export and sharing functions of statistical charts have become increasingly important. This article will introduce how to implement the statistical chart data export and sharing functions of ECharts through the Java interface, and provide specific code examples. 1. Introduction to ECharts ECharts is a data visualization library based on JavaScript and Canvas open sourced by Baidu, with rich charts.

How to use vue and Element-plus to export and print data How to use vue and Element-plus to export and print data Jul 18, 2023 am 09:13 AM

How to use Vue and ElementPlus to implement data export and print functions. In recent years, with the rapid development of front-end development, more and more web applications need to provide data export and print functions to meet users' diverse needs for data use. As a popular JavaScript framework, Vue can easily implement data export and printing functions when used with the ElementPlus component library. This article will introduce a data export and

How to use PHP to implement data import and export Excel functions How to use PHP to implement data import and export Excel functions Sep 06, 2023 am 10:06 AM

How to use PHP to implement data import and export Excel functions. Importing and exporting Excel files is one of the common needs in web development. By using the PHP language, we can easily implement this function. In this article, we will introduce how to use PHP and the PHPExcel library to implement data import and export functions into Excel files. First, we need to install the PHPExcel library. You can download it from the official website (https://github.com/PHPOffice/P

PHP form processing: form data export and printing PHP form processing: form data export and printing Aug 09, 2023 pm 03:48 PM

PHP form processing: form data export and printing In website development, forms are an indispensable part. When a form on the website is filled out and submitted by the user, the developer needs to process the form data. This article will introduce how to use PHP to process form data, and demonstrate how to export the data to an Excel file and print it out. 1. Form submission and basic processing First, you need to create an HTML form for users to fill in and submit data. Let's say we have a simple feedback form with name, email, and comments. HTM

How to use Vue and Element-UI to implement data import and export functions How to use Vue and Element-UI to implement data import and export functions Jul 22, 2023 pm 01:25 PM

How to use Vue and Element-UI to implement data import and export functions. In recent years, with the development of web applications, data import and export functions have become more and more important in many projects. Providing users with convenient data import and export functions can not only improve the user experience, but also improve the overall efficiency of the system. This article will introduce how to use Vue and Element-UI to implement data import and export functions, and attach corresponding code examples. 1. Preparation work First, we need to introduce Vu into the project

Golang Practical Combat: Sharing of Implementation Tips for Data Export Function Golang Practical Combat: Sharing of Implementation Tips for Data Export Function Feb 29, 2024 am 09:00 AM

The data export function is a very common requirement in actual development, especially in scenarios such as back-end management systems or data report export. This article will take the Golang language as an example to share the implementation skills of the data export function and give specific code examples. 1. Environment preparation Before starting, make sure you have installed the Golang environment and are familiar with the basic syntax and operations of Golang. In addition, in order to implement the data export function, you may need to use a third-party library, such as github.com/360EntSec

The perfect combination of Vue and Excel: how to export data in batches The perfect combination of Vue and Excel: how to export data in batches Jul 21, 2023 pm 12:13 PM

The perfect combination of Vue and Excel: How to implement batch export of data In many front-end developments, exporting data to Excel is a common requirement. As a popular JavaScript framework, Vue provides many convenient tools and methods to achieve this function. This article will introduce how to use Vue and Excel.js libraries to implement the batch export function of data. First, we need to install the Excel.js library. It can be installed using the npm package manager: npminstall

Detailed explanation of using Golang to implement data export function Detailed explanation of using Golang to implement data export function Feb 28, 2024 pm 01:42 PM

Title: Detailed explanation of data export function using Golang. With the improvement of informatization, many enterprises and organizations need to export data stored in databases into different formats for data analysis, report generation and other purposes. This article will introduce how to use the Golang programming language to implement the data export function, including detailed steps to connect to the database, query data, and export data to files, and provide specific code examples. To connect to the database first, we need to use the database driver provided in Golang, such as da

See all articles