PHP get svg tag from SVG file, and show it in HTML in DIV PHP get svg tag from SVG file, and show it in HTML in DIV php php

PHP get svg tag from SVG file, and show it in HTML in DIV


I found solution, but it is not exactly the answer for my question. So I will not mark it as a answer, but I leave here this solution. Maybe there will be somebody who will need it... :)

I just read file content, then I look for position of string "< svg" , and then substract this piece of code.

PHP

<?php $svg_file = file_get_contents('http://example.com/logo.svg');$find_string   = '<svg';$position = strpos($svg_file, $find_string);$svg_file_new = substr($svg_file, $position);echo "<div style='width:100%; height:100%;' >" . $svg_file_new . "</div>";?>


You were definitely on the right track with you first attempt. I could spot two small problems though:

  1. As you may have guessed, you tried to output a DOMNodeList object, which is what you will get from a call to getElementsByTagName. As the name implies, it is not a single node object but a collection of those so you would be interested in just the first found svg node (item(0) in code below).
  2. DOM* instances do not automatically get converted into strings when printed. Use the C14N() method instead for output.

Code:

$svg_file = <<<END_OF_SVG<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN""http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"><svg xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink" width='300px' height='300px'>    <title>Test</title>    <circle cx='150' cy='150' r='70' style='fill: gold;' /></svg>END_OF_SVG;$doc = new DOMDocument();$doc->loadXML($svg_file);$svg = $doc->getElementsByTagName('svg');echo '<div style="width: 100%; height: 100%;">';echo $svg->item(0)->C14N();echo '</div>';


This seems to be the first hit for this topic in Google. Based on the other replies and what the original question was about, the answer to the original question is that getElementsByTagName returns an array, so you need to take the the first item in that array and use the saveHTML() method of DOMDocument. I made a short utility function to do just that.

function print_svg($file){    $iconfile = new DOMDocument();    $iconfile->load($file);    echo $iconfile->saveHTML($iconfile->getElementsByTagName('svg')[0]);}