Search code examples
phpimagesvg

Include svg in another php generated svg


I am using php to return an svg image based on availability of devices in my network.

The generated svg initially included a background color and three lines of text. This all works well if I use the image in a html page or open it directly in the browser.

Then I wanted to include a small pictogram (also an svg) based on the type of device.

If I call the svg directly the 2nd svg shows If I use the svg in html the 2nd svg will not show (no error icon - just nothing) - but text and background work If I enter a type with no 2nd svg file present, the browser will show an error icon included in the svg, if called from html also the error icon is missing.

What am I missing / messing up? Thanks in advance!

this is the relevant part of the php

<?php

header('Content-Type: image/svg+xml');

$sName = $_GET['name'];
$sIP = $_GET['ip'];
$sCheckFor = $_GET['suche'];
$sType = $_GET['typ'];

#[...] curl and such things

echo '<?xml version="1.0" encoding="utf-8"?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="100">
    <rect x="0" y="0" width="200" height="100" style="fill: ' . htmlspecialchars( $color, ENT_QUOTES ) . '"/>
    <text fill="' . $sTextColor . '" font-size="24" x="50%" y="25" dominant-baseline="middle" text-anchor="middle">' . str_replace("_", " ", $sName) . ' </text>
    <text fill="' . $sTextColor . '" font-size="12" x="50%" y="52" dominant-baseline="middle" text-anchor="middle">' . $sIP  . ' </text>
    <text fill="' . $sTextColor . '" font-size="18" x="50%" y="75" dominant-baseline="middle" text-anchor="middle">' . $response  . ' </text>';
    echo '<image x="10%" y="32%" width="50px" height="50px" href="./icons/' . $sType . '.svg" />';
    echo '</svg>';

and this the the html file:

<img src="./checkDevice.php?name=AmbiLamp&suche=AmbiLamp&ip=192.168.88.88&typ=lmp">

Solution

  • This is a common problem when nesting SVG's within one another.

    The issue you're having is being caused by the containing SVG viewBox. SVG's have a box size which defines how large to make the area the SVG elements can be displayed within.

    The child SVG is inheriting the viewBox of the parent, which is most likely larger than you're needing, causing the SVG to display, but outside of the area intended.

    A simple solution is to ensure both SVG's have the same viewBox sizing, but this sometimes isn't always easy to implement effectively.