亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 WordPress 數據庫表導出到包含所有元信息的 Excel 文件

將 WordPress 數據庫表導出到包含所有元信息的 Excel 文件

PHP
江戶川亂折騰 2023-07-08 17:46:50
我嘗試從 WordPress 數據庫表導出 Excel 文件users。一般情況下是有效的。但我還需要將所有 user_meta 數據添加到此文件中。我怎樣才能把這個結合起來呢?我的代碼:<?php//Include the wp-load.php fileinclude('../../../../wp-load.php');//As this is external file, we aren't using the WP theme here. So setting this as falsedefine('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;
查看完整描述

1 回答

?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

對于自定義的 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) {

    $meta_row = [];

    foreach ($keys as $meta_key) {

        $value = get_user_meta($user_id, $meta_key, true);

        $meta_row[$meta_key] = $value;

    }

    return $meta_row;

}


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

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


if (empty($results)) {

    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) {

    // load the custom meta for this user's ID:

    $custom_meta_row = load_user_meta($row['ID'], $meta_keys);

    // merge the acquired user meta into the row output:

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

}


$csv_output .= "\n";

如果meta_key并非所有用戶都存在某個特定的情況,這仍然有效,因為get_user_meta將為這些情況生成一個空字符串。


附加說明:按照您的方式生成 CSV 輸出通常不是一個好主意。只要你的任何地方都沒有"and;字符,這種方法就有效user_meta- 這些字符必須使用特定的轉義字符進行轉義。因此,最好fputcsv在輸出流(  $outstream = fopen("php://output", 'w');)上使用。


查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 181 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號