moodle/lib/filelib.php
defacer a43b5308c8 Fixed a typo in get_records_csv.
Made put_records_csv accept array of arrays as well as array of objects.
2005-02-25 02:06:42 +00:00

100 lines
2.3 KiB
PHP

<?php //$Id$
function get_records_csv($file, $table) {
global $CFG, $db;
if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
return false;
}
if(!($handle = @fopen($file, 'r'))) {
error('get_records_csv failed to open '.$file);
}
$fieldnames = fgetcsv($handle, 4096);
if(empty($fieldnames)) {
fclose($handle);
return false;
}
$columns = array();
foreach($metacolumns as $metacolumn) {
$ord = array_search($metacolumn->name, $fieldnames);
if(is_int($ord)) {
$columns[$metacolumn->name] = $ord;
}
}
$rows = array();
while (($data = fgetcsv($handle, 4096)) !== false) {
$item = new stdClass;
foreach($columns as $name => $ord) {
$item->$name = $data[$ord];
}
$rows[] = $item;
}
fclose($handle);
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);
}
$proto = reset($records);
if(is_object($proto)) {
$fields_records = array_keys(get_object_vars($proto));
}
else if(is_array($proto)) {
$fields_records = array_keys($proto);
}
else {
return false;
}
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) {
$array = (array)$record;
$values = array();
foreach($fields as $field) {
if(strpos($array[$field], ',')) {
$values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
}
else {
$values[] = $array[$field];
}
}
fwrite($fp, implode(',', $values)."\r\n");
}
fclose($fp);
return true;
}
?>