PHP Error with Dynamically Generated Responsive SVG Graphs – Scaling Issue

Hi everyone,

I’m working on dynamically generating SVG graphs using PHP, and I’m encountering an issue when trying to make them responsive. I’ve followed the advice on (view.sitepoint.com/make-responsive-svg-graphs-infographics/) and set the viewBox to make the SVG scalable. However, when the graph is resized, it doesn’t scale properly and some elements, like text, don’t adjust accordingly.

Here’s a simplified version of my PHP code that generates the SVG:

<?php
$width = 500;
$height = 500;
echo '<svg width="100%" height="100%" viewBox="0 0 ' . $width . ' ' . $height . '" xmlns="http://www.w3.org/2000/svg">';
echo '<rect width="100%" height="100%" fill="#f0f0f0" />';
echo '<circle cx="250" cy="250" r="100" fill="#007bff" />';
echo '<text x="250" y="250" text-anchor="middle" fill="#ffffff" font-size="20">Graph</text>';
echo '</svg>';
?>

I have set the width and height to 100%, and I’m dynamically setting the viewBox attributes based on the $width and $height variables.

However, when I scale down the browser window, the circle and text elements don’t resize properly. The text stays too large, and the circle is cut off. I also tried adding some CSS media queries to adjust the text size:

@media (max-width: 500px) {
    svg {
        width: 100%;
        height: auto;
    }
    text {
        font-size: 15px;
    }
}

he issue is still present, and I’m wondering if it’s something related to how PHP generates the SVG dynamically or if it’s an issue with the scaling logic.

Has anyone faced this problem before? I would really appreciate some guidance on how to get the text and elements to scale properly in responsive views.

Thanks!

This really looks more like a CSS type of problem. But what I would ask is to see not the PHP code, but the resulting HTML/SGV code that the PHP creates, along with the relevant CSS. That way it can be looked upon as a CSS/SVG problem.
Of course, if the PHP produced SVG is malformed, it may be bounced back to PHP.

PHP doesnt ‘generate’ the SVG.

the SVG is rendered by the browser using flat HTML - the output of PHP.

The resultant HTML, taken out of context, behaves exactly as i would expect it to without intervening code.

I would suspect errant CSS from outside the example to be causing problems if you’re seeing them… but without seeing your page, we’d just be guessing.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.