Home > OS >  How to properly show generated SVG from PHP
How to properly show generated SVG from PHP

Time:02-05

I am generating svg qr codes via php and getting result in php file the following code:

generate-svg.php

<?xml version="1.0" encoding="utf-8"?>
<!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" xml:space="preserve" xmlns:xlink="http://www.w3.org/1999/xlink" width="111" height="111" viewBox="0 0 111 111">
<desc></desc>
<rect width="111" height="111" fill="#ffffff" cx="0" cy="0" />
<defs>
<rect id="p" width="3" height="3" />
</defs>
<g fill="#000000">
<use x="12" y="12" xlink:href="#p" />
</g>
</svg>

Then I need to paste this svg code as an image into another php file. I do it like this:

svg.php

<?
echo '<object type="image/svg xml" data="generate-svg.php" ></object>';
?>

But I need to get the svg code and paste it as a picture. How can I do that?

CodePudding user response:

One of the ways is to display the SVG by echoing the generated SVG thru the PHP file_get_contents command

So say if the generate-svg.php is like the following (As an example, I generate a red circle):

DEMO

<!DOCTYPE html>
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" xmlns:xlink="http://www.w3.org/1999/xlink" width="111" height="111" viewBox="0 0 111 111">

  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />

</svg>

Then use the following to display it (along with other things you want to display):

DEMO

<?php 
echo "This is a line <br>";
echo file_get_contents("generate-svg.php"); 
echo "<br>This is another line <br>";
?>

CodePudding user response:

<img src="/generated-svg.svg" height="200" width="200" alt="QR code">

  • Related