将 WordPress 数据库表导出到包含所有元信息的 Excel 文件

我尝试从 WordPress 数据库表导出 Excel 文件users。一般情况下是有效的。但我还需要将所有 user_meta 数据添加到此文件中。我怎样才能把这个结合起来呢?


我的代码:


<?php

//Include the wp-load.php file

include('../../../../wp-load.php');

//As this is external file, we aren't using the WP theme here. So setting this as false

define('WP_USE_THEMES', false);


global $wpdb;


$table_name = $wpdb->prefix . 'users';

$file = 'email_csv'; // ?? not defined in original code

$results = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A);


if (empty($results)) {

    return;

}


$csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;


foreach ($results as $row) {

    $csv_output .= '"'.implode('";"',$row).'";'."\n";

}

$csv_output .= "\n";


$filename = $file."_".date("Y-m-d_H-i",time());

header("Content-type: application/vnd.ms-excel");

header("Content-disposition: csv" . date("Y-m-d") . ".csv");

header( "Content-disposition: filename=".$filename.".csv");

print $csv_output;

exit;


江户川乱折腾
浏览 162回答 1
1回答

婷婷同学_

对于自定义的 meta_keys 列表(company、firstname、address),您可以定义一个包含这些的数组,并将它们作为尾随列添加到 CSV 中,如下所示:global $wpdb;// Define your custom meta keys you want to add as columns HERE:$meta_keys = ['company', 'firstname', `address`]; // can contain as many as you want// This function will load the desired keys as an associative array// in the form: [$meta_key_1 => $meta_value_1, ..., $meta_key_n => $meta_value_n]function load_user_meta($user_id, $keys) {&nbsp; &nbsp; $meta_row = [];&nbsp; &nbsp; foreach ($keys as $meta_key) {&nbsp; &nbsp; &nbsp; &nbsp; $value = get_user_meta($user_id, $meta_key, true);&nbsp; &nbsp; &nbsp; &nbsp; $meta_row[$meta_key] = $value;&nbsp; &nbsp; }&nbsp; &nbsp; return $meta_row;}$table_name = $wpdb->prefix . 'users';$results = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A);if (empty($results)) {&nbsp; &nbsp; return;}// Merge the result's keys with the list of custom meta keys:$csv_output = '"'.implode('";"',array_merge(array_keys($results[0]), $meta_keys )).'";'."\n";foreach ($results as $row) {&nbsp; &nbsp; // load the custom meta for this user's ID:&nbsp; &nbsp; $custom_meta_row = load_user_meta($row['ID'], $meta_keys);&nbsp; &nbsp; // merge the acquired user meta into the row output:&nbsp; &nbsp; $csv_output .= '"'.implode('";"',array_merge($row, $custom_meta_row)).'";'."\n";}$csv_output .= "\n";如果meta_key并非所有用户都存在某个特定的情况,这仍然有效,因为get_user_meta将为这些情况生成一个空字符串。附加说明:按照您的方式生成 CSV 输出通常不是一个好主意。只要你的任何地方都没有"and;字符,这种方法就有效user_meta- 这些字符必须使用特定的转义字符进行转义。因此,最好fputcsv在输出流(&nbsp; $outstream = fopen("php://output", 'w');)上使用。
打开App,查看更多内容
随时随地看视频慕课网APP