使用php从给定的Google图表api URL下载图像文件

Yas*_*sir 2 php

我想使用类似<a href="">Download</a>的链接下载此URL返回的图像,并且单击该链接时应出现下载框,以便用户可以将图像保存到他/她的系统中。这是返回图片的网址

http://chart.apis.google.com/chart?chs=300x300&cht=qr&chld=L|0&chl=http%253A%252F%252Fnetcane.com%252Fprojects%252Fyourl%252F3
Run Code Online (Sandbox Code Playgroud)

我不想将图像保存到服务器吗?

Tre*_*non 5

原始问题

您可以通过在服务器上设置简单的PHP下载脚本,将文件流式传输或代理给用户。当用户点击download.php下面的脚本时,它将设置正确的标题,以便他们的浏览器要求他们保存下载。然后它将图表图像从谷歌流到用户浏览器。

在您的HTML中:

<a href="download.php">Download</a>
Run Code Online (Sandbox Code Playgroud)

在download.php中:

header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="chart.png"');
$image = file_get_contents('http://chart.apis.google.com/chart?chs=300x300&cht=qr&chld=L|0&chl=http%253A%252F%252Fnetcane.com%252Fprojects%252Fyourl%252F3');
header('Content-Length: ' . strlen($image));
echo $image;
Run Code Online (Sandbox Code Playgroud)

传递动态生成的图表API URL

在您的HTML中:

<?php
$url = 'http://chart.apis.google.com/chart?my-generated-chart-api-url';
<a href="download.php?url=<?php echo urlencode($url); ?>">Download</a>
Run Code Online (Sandbox Code Playgroud)

在download.php中:

$url = '';
if(array_key_exists('url', $_GET)
   and filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
     $url = $_GET['url'];
}
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="chart.png"');
$image = file_get_contents($url);
header('Content-Length: ' . strlen($image));
echo $image;
Run Code Online (Sandbox Code Playgroud)