I've been writing a bit of PHP, SVG and JavaScript. Creating nested XML nodes with a procedural language can be a pain, PHP is no exception here. I wrote a quick PHP function to help with my SVG node creation.

It's nothing fancy, I just thought I'd save somebody the time of writing it themselves:

function make($domxml, $element, $attrs = null, $children = null) {
  $node = $domxml->create_element_ns("http://www.w3.org/2000/svg", $element, "svg");
  if($attrs != null) {
    foreach($attrs as $key => $value) {
      $node->set_attribute($key, $value);
  if($children != null) {
    foreach($children as $child) { $node->append_child($child); }
  return $node;

Simple usage to create a <g> element and append it to the <svg> element $svgnode. ($doc in this context is the DOM XML object i.e. the "document" in JavaScript):

$svgnode->append_child(make($doc, "g"));

To set several attributes, you send an array of attribute name/value pairs to the function:

$svgnode->append_child(make($doc, "circle", array("cx" => 35.5, "cy" => -12.5, "fill" => "blue")));

To append children to the node you're creating, fill an array with the nodes:

$svgnode->append_child( make($doc, "linearGradient",
               array("x1" => 0.0, "y1" => 0.0, "x2" => 1.0, "y2" => 1.0),
               array(make($out, "stop", array("offset" => 0.0, "stop-color" => "#ffffff")),
                     make($out, "stop", array("offset" => 1.0, "stop-color" => "#cccccc")))));

You can use this technique to create a tree of nodes to an arbitrary depth, though the biggest pain with using this technique is getting the correct number of right parentheses, make sure you have a good editor to match them up.

§218 · January 28, 2006 · PHP, Software, SVG, Technology, Tips, Web, XML · · [Print]

2 Comments to “Make SVG From PHP”

  1. Faisal... says:

    Coding in PHP was the work-around to display my SVG files from servers with no SVG mime types. I am happy I got a solution and thanks again for guiding me in the right direction.

    You can check them on my sites:

    I used your javascript code on the second one to keep it compatible. I will credit you, do not worry.

  2. nandh says:


    need help

    i have developed a psvg file that supports both php and svg coding. the code is


    px” height=”px”
    This is a php-random rectangle test
    px” y=”300″ style=”font-size:15;”
    text-anchor=”middle”>The servers Date and Time is:

    px” y=”340″ style=”font-size:15;”
    text-anchor=”middle”>You are running:
    px” y=”360″ style=”font-size:15;”

    i downloaded it from the net. i am using apache server and i have configured my server to support the psvg file. but still the program is not working.

    where as with php extension its working but not showing the server which i run.