mirror of
https://github.com/moodle/moodle.git
synced 2025-01-19 06:18:28 +01:00
Added function put_records_csv. This will be used to convert the results of
the Olson DST parser to csv format prior to importing. Could find other uses as well.
This commit is contained in:
parent
13222d99b5
commit
a77b98ebe6
@ -7,7 +7,7 @@ function get_records_csv($file, $tablename) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!($handle = fopen($file, 'r'))) {
|
||||
if(!($handle = @fopen($file, 'r'))) {
|
||||
error('get_records_csv failed to open '.$file);
|
||||
}
|
||||
|
||||
@ -40,4 +40,50 @@ function get_records_csv($file, $tablename) {
|
||||
return $rows;
|
||||
}
|
||||
|
||||
?>
|
||||
function put_records_csv($file, $records, $table = NULL) {
|
||||
global $CFG, $db;
|
||||
|
||||
if(empty($records)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$metacolumns = NULL;
|
||||
if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
|
||||
error('put_records_csv failed to open '.$file);
|
||||
}
|
||||
|
||||
$fields_records = array_keys(get_object_vars(reset($records)));
|
||||
|
||||
if(!empty($metacolumns)) {
|
||||
$fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
|
||||
$fields = array_intersect($fields_records, $fields_table);
|
||||
}
|
||||
else {
|
||||
$fields = $fields_records;
|
||||
}
|
||||
|
||||
fwrite($fp, implode(',', $fields));
|
||||
fwrite($fp, "\r\n");
|
||||
|
||||
foreach($records as $record) {
|
||||
$values = array();
|
||||
foreach($fields as $field) {
|
||||
if(strpos($record->$field, ',')) {
|
||||
$values[] = '"'.str_replace('"', '\"', $record->$field).'"';
|
||||
}
|
||||
else {
|
||||
$values[] = $record->$field;
|
||||
}
|
||||
}
|
||||
fwrite($fp, implode(',', $values)."\r\n");
|
||||
}
|
||||
|
||||
fclose($fp);
|
||||
return true;
|
||||
}
|
||||
|
||||
?>
|
||||
|
Loading…
x
Reference in New Issue
Block a user