how to extract height and width from a svg file

2019-07-25 16:06发布

问题:

example:

<svg width="23" height="22" xmlns="http://www.w3.org/2000/svg">
<!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
<g>
<title>Layer 1</title>
<path fill-opacity="0" id="svg_1" d="m23,2-20,9.5l22,9" stroke-width="4" stroke="#000000" fill="#ffffff" />
</g>
</svg>

I want to extract the width and height of the svg file so that I can do some positioning with canvg.

I know it's xml, but I can't figure it out. It's probably something really easy but it's the last day of the year and I can't figure it out.

Been trying:

PHP SimpleXML

$xml = simplexml_load_file($imageright) or die("Error: Cannot create object");
print_r($xml->getDocNamespaces());echo '</br>';

giving me Array ( [] => http://www.w3.org/2000/svg )

This also doesn't work:

foreach($xml->svg[0]->attributes() as $a => $b)
  {
  echo $a,'="',$b,"\"</br>";
  }

Any ideas?

回答1:

All you need is

$xml = simplexml_load_file($imageright);
$attr = $xml->attributes();
printf("%s x %s", $attr->width, $attr->height);

Output

23 x 22

Simple Online Demo



回答2:

Here is a simple solution with awk script.

Assuming the width height always in first line.

Dissect the line by " as field separator , then get 2nd and 4th fields.

awk -F '\"' 'NR==1{print $2,$4}' input.svg

Output

23 22