5

How can I loop through SVG elements with PHP?

<?php

$svgString = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="overflow: hidden; position: relative;" width="9140" version="1.1" height="3050">
<rect x="0" y="0" width="9140" height="3050" r="0" rx="0" ry="0" fill="#FFFF00" stroke="#000"/>
<image x="-101.5" y="-113.5" width="203" height="227" xlink:href="1.jpg" stroke-width="1"></image>
<image x="-201.5" y="-213.5" width="103" height="127" xlink:href="2.jpg" stroke-width="1"></image>
</svg>';

$svg = new SimpleXMLElement( $svgString );
$result = $svg->xpath('//image');
echo count( $result ); 
for ($i = 0; $i < count($result); $i++) 
{
    var_dump( $result[$i] );
}

count($result) returns 0 so the loop is omitted.

What am I doing wrong?

hakre
  • 193,403
  • 52
  • 435
  • 836
user2015338
  • 262
  • 2
  • 4
  • 13

2 Answers2

12

The svg document is using a default namespace:

<svg xmlns="http://www.w3.org/2000/svg" ...

Further, the xlink namespace is used for image@href attributes. You need to register the default namespace and the xlink namespace using registerXPathNamespace():

$svg = new SimpleXMLElement( $svgString );

// register the default namespace
$svg->registerXPathNamespace('svg', 'http://www.w3.org/2000/svg');
// required for the <image xlink:href=" ... attribute
$svg->registerXPathNamespace('xlink', 'http://www.w3.org/1999/xlink');

// use the prefixes in the query
$result = $svg->xpath('//svg:image/@xlink:href');

echo count( $result ); // output: '2'
for ($i = 0; $i < count($result); $i++)
{
    var_dump( $result[$i] );
}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Thank you. I am having similar issue with xlink:href. I tried $svg->registerXPathNamespace('xlink', 'http://www.w3.org/1999/xlink'); but it doesn;t seem to work. Please could you help? – user2015338 Apr 26 '13 at 01:01
  • Updated answer. Now its using the xlink namespace as well to fetch href attributes. – hek2mgl Apr 26 '13 at 01:07
  • I am getting : "Warning: SimpleXMLElement::__construct(): namespace error : Namespace prefix xlink for href on use is not defined ..." when I am trying to do : new SimpleXMLElement('' ); – user2015338 Apr 26 '13 at 01:15
  • Why doing this: `new SimpleXMLElement('' );`?! – hek2mgl Apr 26 '13 at 01:21
  • '' is only a shorten piece to paste in here.I need to replace – user2015338 Apr 26 '13 at 01:27
  • `` is never a valid xml document. So therefore it fails. However, this is off topic for this question. Consider to ask a separate question on this – hek2mgl Apr 26 '13 at 01:28
  • I just did, thank you for your help again – user2015338 Apr 26 '13 at 01:45
3

Oh joy, namespaces:

$svg = new SimpleXMLElement( $svg );
$namespaces = $svg->getDocNamespaces();
$svg->registerXPathNamespace('__nons', $namespaces['']);

$result = $svg->xpath('//__nons:image');
Wrikken
  • 69,272
  • 8
  • 97
  • 136