-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.php
92 lines (87 loc) · 2.3 KB
/
csv.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
82
83
84
85
86
87
88
89
90
91
92
<?php
$properties = [
'location' => 'P276',
'place of birth' => 'P19',
'residence' => 'P551',
'educated at' => 'P69',
'employer' => 'P108',
'work location' => 'P937',
'place of death' => 'P20',
];
$data = getData();
foreach ($properties as $prop) {
$data = array_merge($data, getData($prop));
}
makeCsv($data);
function makeCsv($data)
{
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($data)));
foreach ($data as $row) {
fputcsv($df, $row);
}
fclose($df);
echo ob_get_clean();
}
function getData($property = false)
{
$itemWithCoord = "?item";
$propStmt = "";
if ($property) {
$itemWithCoord = "?itemWithCoord";
$propStmt = "?item wdt:$property $itemWithCoord .";
}
$query = "
select ?title ?item ?sitelink ?latitude ?longitude where {
$propStmt
{ $itemWithCoord wdt:P131 wd:Q606212 } UNION { $itemWithCoord wdt:P131 wd:Q604376 } .
?sitelink schema:about ?item .
FILTER EXISTS {
?sitelink schema:inLanguage 'en' .
?sitelink schema:isPartOf <https://en.wikipedia.org/>
} .
$itemWithCoord p:P625 ?coordinate .
?coordinate psv:P625 ?coordinate_node .
?coordinate_node wikibase:geoLatitude ?latitude .
?coordinate_node wikibase:geoLongitude ?longitude .
?item rdfs:label ?title .
FILTER (LANG(?title) = 'en') .
}
";
$data = [];
$xml = getXml($query);
foreach ($xml->results->result as $res) {
$data[] = getBindings($res);
}
return $data;
}
function getXml($query)
{
$url = "https://query.wikidata.org/bigdata/namespace/wdq/sparql?query=" . urlencode($query);
try {
$result = file_get_contents($url);
} catch (\Exception $e) {
throw new \Exception("Unable to run query: <pre>" . htmlspecialchars($query) . "</pre>", 500);
}
if (empty($result)) {
header('Content-type:text/plain');
echo $query;
exit(1);
}
$xml = new \SimpleXmlElement($result);
return $xml;
}
function getBindings($xml)
{
$out = [];
foreach ($xml->binding as $binding) {
if (isset($binding->literal)) {
$out[(string)$binding['name']] = (string)$binding->literal;
}
if (isset($binding->uri)) {
$out[(string)$binding['name']] = (string)$binding->uri;
}
}
return $out;
}