-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetCoordinates.php
103 lines (77 loc) · 2.2 KB
/
getCoordinates.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
93
94
95
96
97
98
99
100
101
102
<?php
require_once 'include.php';
require_once 'Buzz/lib/Buzz/Browser.php';
use Symfony\Component\Yaml\Yaml;
$apiString = '';
$api = array(
'format' => 'json',
'action' => 'query',
'prop' => 'revisions',
'rvprop' => 'content',
'redirects' => 'true'
);
foreach ($api as $k => $v)
{
$apiString .= sprintf('%s=%s&', $k, $v);
}
$lines = Yaml::parse(stream_get_contents(STDIN));
$client = new Buzz\Client\Curl();
$curl = $client->getCurl();
curl_setopt($curl, CURLOPT_USERAGENT, 'Railway station scraper ([email protected])');
$browser = new Buzz\Browser($client);
$error = 0;
$stations = array();
foreach ($lines as $line)
{
$stations = array_merge($stations, $line['stations']);
}
$stationsUnique = array_unique($stations);
sort($stationsUnique);
$full = array();
foreach ($stationsUnique as $station)
{
$foundError = false;
$response = $browser->get('http://en.wikipedia.org/w/api.php?' . $apiString . 'titles=' . urlencode(str_replace(' ', '_', $station . ' railway station')));
$contentJson = $response->getContent();
$contentTmp = json_decode($contentJson, true);
$page = reset($contentTmp['query']['pages']);
if (key($contentTmp['query']['pages']) == -1)
{
fwrite(STDERR, sprintf("Could not find station '%s'.\n", $station));
$foundError = true;
}
else
{
preg_match('/latitude(\s*)\=(\s*)(\-*)([0-9]+)\.([0-9]+)/', $page['revisions'][0]['*'], $latMatches);
preg_match('/longitude(\s*)\=(\s*)(\-*)([0-9]+)\.([0-9]+)/', $page['revisions'][0]['*'],
$lngMatches);
if (!(empty($latMatches) || empty($lngMatches)))
{
$fullTmp = array(
'origName' => $station,
'name' => $page['title'],
'lat' => sprintf('%s%s.%s', $latMatches[3], $latMatches[4], $latMatches[5]),
'lng' => sprintf('%s%s.%s', $lngMatches[3], $lngMatches[4], $lngMatches[5])
);
}
else
{
fwrite(STDERR, sprintf("No co-ordinates found for station '%s' (checking article '%s').\n", $station, $page['title']));
$foundError = true;
}
}
if (!$foundError)
{
$full[] = $fullTmp;
}
else
{
$error++;
}
}
if ($error)
{
fwrite(STDERR, 'Could not find ' . $error . ' station(s). Please check and correct the name(s) as appropriate.' . "\n");
die();
}
echo Yaml::Dump(array($lines, $full));