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

Patrik picture Patrik · May 1, 2015 · Viewed 29.5k times · Source

I want to read an SVG file and get the SVG tag from this file (because I want to show svg in html e.g. <div><svg>...</svg></div> without the xml header).

And show this svg tag in browser like HTML - print this SVG TAG like SVG image. Becouse now I'm gettong wrong output "DOMNodeList Object ( [length] => 1 ) ".

PHP

$doc = new DOMDocument();
$doc->load('http://example.com/logo.svg');
$svg = $doc->getElementsByTagName('svg');

echo "<div style='width: 100%, height: 100%; '>";
print_r($svg); // DOMNodeList Object ( [length] => 1 ) 
echo "</div>";

Answer

Patrik picture Patrik · May 2, 2015

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>";

?>