How do you get the width and height of an SVG picture in PHP?

Viewed 39476

I tried to use getimagesize() on an SVG file, but it failed.

I know that SVG is “Scalable Vector Graphics”, but I find that Google Chrome’s “Review elements” can perfectly get the dimensions of an SVG picture, so I suspect that this is also possible in PHP.

If it is difficult to get the dimensions, is there any way to judge whether an SVG picture is vertical or horizontal?

6 Answers

Here's a quick and dirty hack to check the viewbox size with regex. It works in most cases but do see the other answers to get an idea of its limitations.

preg_match("#viewbox=[\"']\d* \d* (\d*) (\d*)#i", file_get_contents('file.svg'), $d);
$width = $d[1];
$height = $d[2];

with simplexml_load_file

$svgXML = simplexml_load_file($imgUri);
list($originX, $originY, $relWidth, $relHeight) = explode(' ', $svgXML['viewBox']);

with preg_match regex (this one does for int and float values in viewBow values)

preg_match("#viewbox=[\"']\d* \d* (\d*+(\.?+\d*)) (\d*+(\.?+\d*))#i", file_get_contents($imgUri), $d);
$relWidth = (float) $d[1];
$relHeight = (float) $d[3];
Related