如何下载 Google 的 KML 文件

How to download Google's KML file

我知道 this link Google 中说它不再可用。

但是,如果您只是 运行 一个脚本来创建 link 像这样:

    $timespan = [
        'year'  => '2015',
        'month'=> '0',
        'day'   => '28',
    ];
    $path = 'https://www.google.com/maps/timeline/kml?authuser=0&pb=!1m8!1m3!1i'.$timespan['year'].'!2i'.$timespan['month'].'!3i'.$timespan['day'].'!2m3!1i'.$timespan['year'].'!2i'.$timespan['month'].'!3i'.$timespan['day'];

    echo "<a href='".$path."'>link</a>";

您会发现您实际上可以下载特定日期的 kml 历史文件,您可以轻松地创建自己的数据。这个问题是我不能以编程方式做到这一点。所以,如果我去打开我的浏览器,它会下载,但是 file_get_contents 例如 - 当然 - 不起作用。

我尝试使用 Postman 的 Inceptor 重新发送请求,以便以编程方式模拟它。但是我无法成功发送成功的请求。 Google 以 400 页面响应。

有什么方法可以模仿浏览器的行为以便我可以下载文件吗?

通过file_get_contents请求失败,因为Google服务器需要授权调用,从下图可以看出(Cookie头包含所谓的身份验证令牌 例如 HSIDSSIDSID)

关于身份验证令牌

Google 使用 Security cookies:

to authenticate users, prevent fraudulent use of login credentials, and protect user data from unauthorized parties.

This python example(参见GetAuthTokens函数)演示如何获取身份验证令牌。

例子

以下示例演示如何通过指定安全 cookie 执行 授权 调用:

$authTokens = array(
   'HSID' => '',
    'SSID' => '',
    'SID' => '',
);

$opts = array(
    'http'=>array(
        'method'=>"GET",
        'header'=>
            'Cookie: HSID=' . $authTokens["HSID"] . '; SSID=' . $authTokens["SSID"] . '; SID=' . $authTokens["SID"]
    )
);

$context = stream_context_create($opts);
$content = file_get_contents($url,false, $context);