-
Notifications
You must be signed in to change notification settings - Fork 2
/
v3.php
81 lines (66 loc) · 2.14 KB
/
v3.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/**
* Created by PhpStorm.
* User: yousan
* Date: 2019-03-08
* Time: 18:17
*/
function main1() {
// https://docs.google.com/spreadsheets/d/1m4BI7R-CcjNREH4DUe1xCM3OIVVSGrGx6-7iUtIvUWE/edit#gid=635058114
// スプレッドシートのID
$gss_id = '1m4BI7R-CcjNREH4DUe1xCM3OIVVSGrGx6-7iUtIvUWE';
// シートID
$gid = '635058114';
$url = 'https://docs.google.com/spreadsheets/d/' . $gss_id . '/export?format=csv&gid=635058114';
$csv = file_get_contents( $url );
$array = array_map( "str_getcsv", explode( "\n", $csv ) );
$json = json_encode( $array );
var_dump( $json );
echo 'hello';
}
function parseCSV( $url ) {
// @see https://blog.keinos.com/20170523_2295
$file = new NoRewindIterator( new SplFileObject( $url ) );
$file->setFlags( SplFileObject::READ_CSV );
$datas = [];
$header = null;
while ( $row = $file->fgetcsv() ) {
if ( null === $header ) { // 初回の一行目
$header = $row;
continue;
}
if ( count( $row ) === 1 || // 空行だったりした場合
empty( $row[0] ) || // 最初の行はIDで固定だが、そこが省かれている場合には省く
'null' === $row[0] // 最初の列にnullと書いてある行は省く
) {
continue;
}
$data = array_combine( $header, $row );
foreach ( $data as $key => $value ) {
if ( ! is_numeric( $data[ $key ] ) && // emptyが 0 を trueと解釈してしまうため
empty( $data[ $key ] ) ) { // 空行
unset( $data[ $key ] ); // 空行は許されないのでNULLにしておく
}
}
if ( empty( $data['createdAt'] ) ) {
$data['createdAt'] = date( 'U' );
}
if ( empty( $data['modifiedAt'] ) ) {
$data['modifiedAt'] = date( 'U' );
}
$datas[] = $data;
}
return $datas;
}
function main() {
// https://docs.google.com/spreadsheets/d/1m4BI7R-CcjNREH4DUe1xCM3OIVVSGrGx6-7iUtIvUWE/edit#gid=635058114
// スプレッドシートのID
$gss_id = $_GET['gss_id'];
// シートID
$gid = $_GET['gid'];
$url = 'https://docs.google.com/spreadsheets/d/' . $gss_id . '/export?format=csv&gid=' . $gid;
$data = parseCSV($url);
header("Access-Control-Allow-Origin: *");
echo json_encode($data, JSON_PRETTY_PRINT);
}
main();