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

cj333 picture cj333 · Jun 30, 2011 · Viewed 27.9k times · Source

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?

Answer

Brian picture Brian · Jun 30, 2011

An SVG is simply an XML file, so the GD libs will not be of any help!

You should simply be able to parse the XML file to get such properties.

$xml = '
<svg width="500" height="300" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">

<rect x="90" y="10"
    width="400" height="280"
    style="fill: rgb(255,255,255); stroke: rgb(0,0,0); stroke-width: 1; " />
</svg>';

$xmlget = simplexml_load_string($xml);
$xmlattributes = $xmlget->attributes();
$width = (string) $xmlattributes->width; 
$height = (string) $xmlattributes->height;
print_r($width);
print_r($height);

The values need to be cast or they will return an object.