如何将数据从install.xml文件插入moodle中的mysql数据库

时间:2014-07-09 10:28:25

标签: moodle

在moodle站点(使用moodle版本2.6.3)中,我已经通过XMLDB编辑器生成了install.xml文件,但它仅用于在插件安装期间在数据库中创建表。我想在表格中插入一些默认行。

任何正文都可以帮助我如何在install.xml文件中编辑插入数据

                                                                                        

1 个答案:

答案 0 :(得分:1)

要在安装后添加数据,请使用

创建名为yourplugin / db / install.php的文件

更新:添加了xml解析器

defined('MOODLE_INTERNAL') || die;

require_once($CFG->libdir . '/xmlize.php');

function xmldb_yourpluginname_install() {
    global $CFG, $OUTPUT, $DB;
    // Your add data code here.
    $xmltext = file_get_contents('import.xml');
    $records = parse_xml($xmltext, 'records', 'record');
    foreach ($records as $record) {
        $DB->insert_record('yourtablename', $record);
    }
}

/**
 * Converts XML text into an array of stdclass objects.
 *
 * @param type $text - xmltext
 * @param type $elementnames - plural name of elements
 * @param type $elementname - name of element
 * @return array|boolean - array of record objects
 */
function parse_xml($text, $elementnames, $elementname) {
    // Seems that xmlize needs a lot of memory.
    ini_set('memory_limit', '256M');

    // Ensure content is UTF-8.
    $content = xmlize($text, 1, 'UTF-8');

    $records = array();
    if (!empty($content[$elementnames]['#'][$elementname])) {
        $rows = $content[$elementnames]['#'][$elementname];
        foreach ($rows as $row) {
            $fields = $row['#'];
            $row = new stdClass();
            foreach ($fields as $fieldname => $fieldvalue) {
                $row->$fieldname = $fieldvalue[0]['#'];
            }
            $records[] = $row;
        }
        return $records;
    }

    return false;
}