Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

384
Visualizações
PHP - Efficiently displaying inline SVG images

I need to display svg images in my page. Since the svg images will be styled (properties like fill, stroke etc) with css, so the svg has to be inline. Now I also need to set the class attribute ( <svg class="someClass">...</svg>. ) of these svg files dynamically.

Now, my problem is the page can load any number of svg images dynamically. And the class names will all be loaded from an array. As the svg is inline, using a loop to fill the class names is impossible.

So I thought of using json to handle this.

{
    "icon-name-1" : {
          "viewbox" : "0 0 100 100",
          "svgContent" : "..."
    },

    "icon-name-2" : {
          "viewbox" : "0 0 100 100",
          "svgContent" : "..."
    },  

    ...      
}

Then in PHP, I loaded the file to a json_object and use a function to load the icon and finally looping the array, now with the icon names also, to echo the svg.

    $iconObj = json_decode(file_get_contents("icons.json"));

    function load_SVG ($iconObj, $iconName, $svgClassName) {
        $viewbox = $iconObj->viewbox;

        $svg = "<svg class='$svgClassName' viewBox='$viewbox'>";
            $svg .= $iconObj->$iconName->svgContent;
        $svg .= "</svg>";

        return $svg;
    }

    // array is generated dynamically too
    $arr = [
       ["class-name-1", "icon-name-1"],
       ["class-name-2", "icon-name-2"],
       ...
    ];

    foreach ($arr as $item) {
       load_SVG($iconObj, $item[0], $item[1]);
    }

I am getting the feeling I am over-complicating things here. So I'd like to know if there is better way or another way of achieving the same? But one thing I like about this is I don't have to see any inline svg in the code which, for sure, would have been a nightmare :)

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Indeed this was a case of over-complication. All I had to do was use a placeholder like class={{class-name}} in the svg code and then use load the svg file and use a simple string substitution to achieve the same.

$svg = file_get_contents($svgPath);
$svg = str_replace("{{class-name}}", $array[$index], $svg);

The JSON was complete pointless. Lesson learned.

over 4 years ago · Santiago Trujillo Relatório

0

I would say yes. Considering you are doing dynamically, wouldn't it be better to simply replace the class tags, or insert them, via JQuery or javascript? They give you excellent tools to mark all dynamically created tags.

    {<ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
</ul>

$( "content" ).each( function( index, element ){
    console.log( $( this ).text() );
});}

naturally you would have to alter your debugging info into a class altering method instead of just debugging the text.

After reading the comments, I will provide an alternate answer, but I won't claim credit for this.

Someone else answered this question: Is there a better way to write HTML strings in PHP?

The suggestion I would go for is at the bottom of the thread.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda