Search code examples
phpparsingsvgdomdocumentdomxpath

Select and get special svg element by PHP script


Need to get and modify first polygon inside the group g with special (dynamic) id inside SVG file by php script. Couldn't find this element, using DOMDocument() and DOMXPath. Please, help

PHP:

$svg = file_get_contents($svgPath);
$doc = new DOMDocument();
$doc->loadXML($svg);
$doc->preserveWhiteSpace = false;
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('svg','http://www.w3.org/2000/svg');
**$curPolygon = $xpath -> query("//svg:g[@id='fl_1']/polygon[0]");**
if ($curPolygon ) {
  $curPolygon [0]->setAttribute('fill', '#ae8f72');
}
$svg = $doc->saveXML($doc);
echo $svg;

SVG:

<svg>
...
<g id="Flats">

    ...

    <g id="fl_1">
        <polygon fill="none" points="0,0 436.5,0 436.5,197.7 257,197.7 257,267.1 196.9,267.1 196.9,293.9 0,293.9"/>
        <g> <rect x="209.9" y="84.8" fill="#AE8E72" width="56.3" height="22.1"/> </g>
        <text transform="matrix(1 0 0 1 214.1091 101.5043)"><tspan x="0" y="0">4</tspan></text>
        <text transform="matrix(1 0 0 1 235.5047 101.5042)">132,0</text>
    </g>

    <g id="fl_2">
        <polygon fill="none" points="404.5,388.7 404.5,390 251.7,390 251.7,192.3 436.5,192.3 436.5,388.7"/>
        <g> <rect x="327.7" y="278.4" fill="#AE8E72" width="56.3" height="22.1"/> </g>
        <text transform="matrix(1 0 0 1 331.8962 295.0608)"><tspan x="0" y="0">1</tspan></text>
        <text transform="matrix(1 0 0 1 354.9925 295.0607)">40,7</text>
    </g>

    ...
</g>
...
</svg>

Result of var_dump($q) is object(DOMNodeList)#6 (1) { ["length"]=> int(0) }


Solution

  • A couple of things from your code. The first is that you don't seem to load the document...

    $doc->loadXML($svg);
    

    the second part is the XPath expression. I think if you have the namespace svg as the default namespace, then you would need to apply this to both parts of the XPath expression. Also XPath arrays start at 1, so the expression should be

    $curPolygon = $xpath -> query("//svg:g[@id='fl_1']/svg:polygon[1]");