Fixed a typo in get_records_csv.
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
a43b5308 3function get_records_csv($file, $table) {
599f38f9 4 global $CFG, $db;
5
6 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
7 return false;
8 }
9
a77b98eb 10 if(!($handle = @fopen($file, 'r'))) {
599f38f9 11 error('get_records_csv failed to open '.$file);
12 }
13
14 $fieldnames = fgetcsv($handle, 4096);
15 if(empty($fieldnames)) {
16 fclose($handle);
17 return false;
18 }
19
20 $columns = array();
21
22 foreach($metacolumns as $metacolumn) {
23 $ord = array_search($metacolumn->name, $fieldnames);
24 if(is_int($ord)) {
25 $columns[$metacolumn->name] = $ord;
26 }
27 }
28
29 $rows = array();
30
31 while (($data = fgetcsv($handle, 4096)) !== false) {
32 $item = new stdClass;
33 foreach($columns as $name => $ord) {
34 $item->$name = $data[$ord];
35 }
36 $rows[] = $item;
37 }
38
39 fclose($handle);
40 return $rows;
41}
42
a77b98eb 43function put_records_csv($file, $records, $table = NULL) {
44 global $CFG, $db;
45
46 if(empty($records)) {
47 return true;
48 }
49
50 $metacolumns = NULL;
51 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
52 return false;
53 }
54
55 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
56 error('put_records_csv failed to open '.$file);
57 }
58
a43b5308 59 $proto = reset($records);
60 if(is_object($proto)) {
61 $fields_records = array_keys(get_object_vars($proto));
62 }
63 else if(is_array($proto)) {
64 $fields_records = array_keys($proto);
65 }
66 else {
67 return false;
68 }
a77b98eb 69
70 if(!empty($metacolumns)) {
71 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
72 $fields = array_intersect($fields_records, $fields_table);
73 }
74 else {
75 $fields = $fields_records;
76 }
77
78 fwrite($fp, implode(',', $fields));
79 fwrite($fp, "\r\n");
80
81 foreach($records as $record) {
a43b5308 82 $array = (array)$record;
a77b98eb 83 $values = array();
84 foreach($fields as $field) {
a43b5308 85 if(strpos($array[$field], ',')) {
86 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 87 }
88 else {
a43b5308 89 $values[] = $array[$field];
a77b98eb 90 }
91 }
92 fwrite($fp, implode(',', $values)."\r\n");
93 }
94
95 fclose($fp);
96 return true;
97}
98
99?>