599f38f9 |
1 | <?php //$Id$ |
2 | |
3 | function get_records_csv($file, $tablename) { |
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 |
43 | function 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 | |
59 | $fields_records = array_keys(get_object_vars(reset($records))); |
60 | |
61 | if(!empty($metacolumns)) { |
62 | $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns); |
63 | $fields = array_intersect($fields_records, $fields_table); |
64 | } |
65 | else { |
66 | $fields = $fields_records; |
67 | } |
68 | |
69 | fwrite($fp, implode(',', $fields)); |
70 | fwrite($fp, "\r\n"); |
71 | |
72 | foreach($records as $record) { |
73 | $values = array(); |
74 | foreach($fields as $field) { |
75 | if(strpos($record->$field, ',')) { |
76 | $values[] = '"'.str_replace('"', '\"', $record->$field).'"'; |
77 | } |
78 | else { |
79 | $values[] = $record->$field; |
80 | } |
81 | } |
82 | fwrite($fp, implode(',', $values)."\r\n"); |
83 | } |
84 | |
85 | fclose($fp); |
86 | return true; |
87 | } |
88 | |
89 | ?> |