-
Notifications
You must be signed in to change notification settings - Fork 1
/
Convert.php
51 lines (48 loc) · 1.03 KB
/
Convert.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
namespace core;
/**
* Parse content-type
*/
class Convert
{
// Parse CSV into associated array
public static function csv($str, $loose = false)
{
$fp = fopen("php://temp", 'r+');
if (! is_resource($fp)) {
user_error("fopen(temp) failed");
}
if (false === fputs($fp, $str)) {
user_error("fputs(temp) failed");
}
if (! rewind($fp)) {
user_error("rewind(temp) failed");
}
$kv = fgetcsv($fp);
if ($kv === null || $kv === false) {
user_error("fgetcsv(temp) failed");
}
if (substr($kv[0], 0, strlen("sep=")) === "sep=") {
$kv = fgetcsv($fp); // ignore sep= line
}
$lines = [];
while (($data = fgetcsv($fp)) !== false) {
$out = [];
foreach ($kv as $k => $v) {
if (isset($out[ $v ])) {
user_error(sprintf("key=%s already set", $v));
}
if ($loose && !isset($data[$k])) {
$out[ $v ] = "";
continue;
}
if (! isset($data[$k])) {
user_error(sprintf("key=%s missing", $k));
}
$out[ $v ] = trim($data[$k]);
}
$lines[] = $out;
}
return $lines;
}
}