从SVG原始数据创建获取SVG文件内容并下载

时间:2018-03-23 13:34:05

标签: php laravel

我有像这样的SVG原始数据

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100px" height="100px" viewBox="0 0 100 100"><defs><rect id="r0" width="3" height="3" fill="#000000"/></defs><rect x="0" y="0" width="100" height="100" fill="#fefefe"/><use x="12" y="12" xlink:href="#r0"/><use x="15" y="12" xlink:href="#r0"/><use x="18" y="12" xlink:href="#r0"/><use x="21" y="12" xlink:href="#r0"/><use x="24" y="12" xlink:href="#r0"/><use ..............much more lines </svg>

如何将此字符串转换为svg文件内容并将其下载而不将其保存在存储空间或任何地方?有办法吗?

我试过

$data = base64_decode($file);
$im = imagecreatefromstring($data);

但这会引发imagecreatefromstring(): Data is not in a recognized format

2 个答案:

答案 0 :(得分:3)

尝试按以下方式输出图像:

header('Content-type: image/svg+xml');
header('Content-Disposition: attachment; filename=image.svg');
echo $data;

答案 1 :(得分:3)

假设你的$文件包含svg的全部内容

return response($file)->withHeaders(['Content-Type' => "image/svg+xml"]);

这是文档上的内容 12