Add the Graphics Power of SVG to PHP

Add the Graphics Power of SVG to PHP

calable Vector Graphics (SVG) is an XML specification for producing vector-based graphic content that you can create, modify, and manipulate dynamically from programming languages. Here, you’ll explore the most important techniques and libraries for integrating SVG with PHP to create diverse graphic content—from simple shapes to complex graphs. You’ll see how to:

  • Convert an SVG document into a PHP document.
  • Use the object and embed elements to include an SVG document in an XHTML document.
  • Generate SVG using PHP’s echo command.
  • Generate SVG using the phpHtmlLib library.
  • Generate SVG documents using the PEAR::XML_SVG package.
  • Generate SVG documents using the PEAR::Image_Canvas package.
  • Integrate PHP , SVG, and AJAX.

Three Simple Techniques
To get started, here are three of the simplest techniques for using SVG in PHP.

  1. You can convert any SVG document into a PHP document by replacing the .svg extension with the .php extension and specifying the image/svg+xml MIME type using the header() function:
  2.                                                       Basic shapes        
  3. You can include an SVG document (saved with the .php extension) into an XHTML document, through the object or embed element:
  5. You can generate an SVG document dynamically using the echo command:
  6.    ';     echo '';     echo '';     echo '';     echo '';     echo '';     echo '';     echo '       Basic shapes';     echo '';     echo '';   ?>

To go beyond these techniques, it’s best to download some helper packages that provide SVG support—classes and methods that simplify working with, generating, and modifying SVG. The rest of this article explains how to obtain and use these packages.

Generating SVG with phpHtmlLib
One easy way to get solid SVG support is to download phpHtmlLib, an application development framework for developing Model-View-Controller (MVC) object-oriented web applications in PHP. PhpHtmlLib supports AJAX, caching, and rich client web applications, along with a comprehensive set of useful PHP classes and methods for working with HTML and XML documents—including, of course, SVG.

To install phpHtmlLib on your machine follow these steps:

  1. Unzip the archive into an folder.
  2. Copy the file from the {$phpHtmlLib}/examples folder into your applications directory.
  3. Edit to indicate the location of your path file. For example:
  4.    include_once(      '../phpLibs/phphtmllib/');

The base class of phpHtmlLib is Container, which has these direct descendents:

  • XMLTagClass builds and renders XML tags.
  • SVGGraph is the base class for generating SVG graphs.
  • XMLDocument lets you build a complete XML document and render it.

Because SVG is an XML-based language, the XMLTagClass class serves as the base class for an SVGTag class, which you use to set an SVG tag’s attributes and values. Similarly, the XMLDocument class represents the base class for the SVGDocument class, which you use to create a new empty SVG document. You can obtain an SVGDocument instance using the following constructor:

   SVGDocument __construct (      [string $width = "100%"],       [string $height = "100%"]) 

In the preceding code, the $width and $height arguments represent the width and height of the SVG visualization window. Table 1 lists other important methods exposed by the SVGDocument class.

Table 1: Useful Methods: Here are the SVGDocument class’s most important methods, with a brief description of each.
Method Description
void add (mixed $content) This method adds a component to the SVG document. The received argument is a string or a tag object.
string render(
 [int $indent_level = 0],
 [int $output_debug = 0])
This method renders an SVG document. The $indent_level argument represents the indentation level for the container and the output_debug argument represents a compatibility flag.
function svg_circle(
  $cx, $cy, $radius,
This function builds an SVG tag using the center coordinates, radius, and some design parameters.
function svg_ellipse(
  $cx, $cy, $rx, $ry,
This function builds an SVG tag using the center coordinates, the x-axis, and y-axis radius.
function svg_line(
  $x1, $y1, $x2, $y2,
This function builds an SVG tag using the (x1, y1), (x2 ,y2) coordinates and some drawing-style parameters.
function svg_polygon(
This function builds an SVG tag using an array of (x,y) points. The polygon is closed automatically after the last point is specified.
function svg_polyline(
  $points, $fill=”none,”,
Much like a polygon, this function creates an SVG tag using an array of (x,y) coordinates and some drawing-style parameters.
function svg_rect(
  $x, $y, $width,
This function creates an SVG tag using the specified left upper-corner coordinate and the width and height values.
function svg_text(
  $x, $y, $rotate=NULL,
This function builds an SVG tag in which text will be placed at the specified point, rotated to the specified number of degrees.
function svg_g(
This function builds an SVG (graphic container) tag using the specified style and transform parameters.

Drawing Basic Shapes
You build SVG documents using the basic drawing methods listed in Table 1. For example, Listing 1 shows the code for a PHP script that generates an SVG document showing the basic shapes that phpHtmlLib supports (see Figure 1). Note that you must define the PHPHTMLLIB constant that points to the /phphtmllib directory and include the proper phpHtmlLib classes before you can generate the SVG content.

Figure 1. Basic Shapes Using phpHtmlLib: The code in Listing 1 draws basic shapes using the phpHtmlLib library.

The next example generates an SVG document that illustrates how to use the onmouseover and onmouseout events (see Figure 2):

Figure 2. Capturing Mouse Events: This rectangle (initially unfilled) fills with a red color whenever a user moves the mouse pointer over it.
   set_tag_attribute("onmouseover,"      "'style', 'fill:red;');");   $rect->set_tag_attribute("onmouseout,"      "'style', '');");   $svgdoc->add($rect);      print $svgdoc->render();   ?>

The preceding code draws a rectangle with a mouseover script so that when users move the mouse pointer over the rectangle, the code fills the rectangle with red, and when they move the mouse pointer out of the rectangle, the code clears the fill.

Figure 3. Translate and Rotate: The figure shows an ellipse translated and rotated by 45 degrees.

The following example generates an SVG document for drawing an ellipse rotated at a 45-degree angle (see Figure 3):

   set_transform("translate(100 100) rotate(-45)");   $svgdoc->add($ellipse);       print $svgdoc->render();   ?>

Generating SVG Diagrams
Using phpHtmlLib, you can generate SVG diagrams dynamically; however, the library currently supports only line graphs. The base class for graphing operations is SVGGraph; here’s the constructor:

   SVGGraph __construct ( $title,  $width,  $height)

The arguments indicate the graph title, width and height. The SVGGraph class has three important descendants: SVGXYGraph, SVGXYPlotGraph, and SVGXYLineGraph. These classes offer a set of dedicated methods for building SVG graphs, of which the most important are the add_line and add_point methods. Here’s an example of creating a simple graph:

   void add_line (string $x_values,       string $y_values, [string $color = "red"])

This method plots a line graph. The $x and $y arguments are strings of comma-separated numeric values representing the graph coordinates. The last argument (optional) specifies the line color which is set to red by default. To add a point to the graph, you’d use the add_point method:

Figure 4. Generated Line Graph: PHP generated this SVG graph with phpHtmlLib using an SVGGraph-derived class.
   void add_point (string $x, string $y,       [string $color = "red"])

The arguments specify the x and y coordinates of the inserted graph point. As a complete example, here’s the PHP code to generate an SVG document that draws two line graphs (see Figure 4):

   set_grid_line_color("red");      //add a line   $graph->add_line("10,20,23,51,90," "0,9,67,45,90," "black");      //add another line   $graph->add_line("10,48.5,56,89," "9.5,34,56,67," "blue");      //add the graph to SVG document   $svgdoc->add($graph);      //show the SVG   print $svgdoc->render();   ?>

Generating SVG with PEAR::XML_SVG
The phpHtmlLib package is not your only resource for generating SVG. The PEAR::XML_SVG package (v. 1.0.1) is a stable release that provides an object-oriented API for building SVG documents. You can download this PEAR and install it from a shell command (ex. cmd.exe) like this:

   install {complete_XML_SVG_path}

The package contains definitions of its 26 classes in the SVG.php file that you must include in your scripts when using the package:

   require_once 'XML/SVG.php';   

The main classes in the XML_SVG package are:

  • XML_SVG—a wrapper class that provides some examples and a few convenience methods.
  • XML_SVG_Document—used to create an empty SVG document.
  • XML_SVG_Element—the base class for the different SVG element objects. You should extend this class to create new SVG elements.
  • The XML_SVG_Group class, which is used for creating an empty SVG group.
  • The XML_SVG_Rect class, which is used for creating an SVG rectangle.
  • The XML_SVG_Circle class, which is used for creating an SVG circle.
  • The XML_SVG_Line class, which is used for creating a SVG line.
  • The XML_SVG_Text class, which is used for creating SVG text.

The code in Listing 2 generates a simple SVG document that displays some basic shapes (see Figure 5):

Figure 5. Basic Shapes: Using PEAR::XML_SVG, you can easily generate SVG documents that display basic shapes.

The SVG document generated by Listing 2 is:

                                                   Basic shapes        

To insert animation into an SVG document you can use the XML_SVG_Animate class, derived from the XML_SVG_Element class. The constructor takes an array of arguments as follows:

Figure 6. SVG Animation Generated by PEAR::XML_SVG: The green car on the left shows the animation state as it begins, while the red car on the right shows the completed animation.
  • attributeName—Specifies the name of the SVG attribute/CSS property to be animated.
  • attributeType—Specifies the type of the animated SVG attribute/CSS property. The supported values are “XML” and “CSS.”
  • from—Specifies the initial value of the animated SVG attribute/CSS property.
  • to—Specifies the final value of the animated SVG attribute/CSS property.
  • dur—Sets the duration of the animation in seconds.
  • fill—Used to “freeze” the animation after the first run.

As an example, Listing 3 shows the code for a small car animation. Although you have to imagine the animation, it works like this: The car travels from left to right. During the animation, the car’s color changes from green to red. A text animation runs simultaneously that modifies the color and size of the text (see Figure 6).

Generating SVG with PEAR::Image_Canvas
This package provides a common interface for drawing images; the images created are independent of the library. The package is still in alpha relase (the latest released version is 0.3.1). You can download this PEAR and install it from a command-line prompt like this:

   install {complete_Image_Canvas_path}
Author’s Note: Documentation for this library is difficult to find and not well arranged, so I’ve provided some for the most common and useful methods in the sidebar “PEAR::Image_Canvas Methods.”

Figure 7. Basic Shapes: You can draw nice-looking basic shapes, controlling borders and fill gradients using PEAR::Image_Canvas.

Here’s some sample code that generates an SVG document for drawing the basic shapes supported by the Image_Canvas package (see Figure 7):

   400,'height'=>300));      $Canvas->setLineColor('black');   $Canvas->rectangle(array(      'x0'=>0,'y0'=>0,'x1'=>210,'y1'=>170));      $Canvas->setGradientFill(array(      'direction' => 'horizontal',       'start' => 'orange',       'end' => 'brown'));   $Canvas->setLineColor('red');   $Canvas->ellipse(array('x' => 75,       'y' => 55, 'rx' => 40, 'ry' => 30));   $Canvas->setFont(array(      'name' => 'Arial', 'size' => 12));   $Canvas->addText(array(      'x' => 58, 'y' => 90,       'text' => 'Ellipse','color'=>'orange'));      $Canvas->setGradientFill(array(      'direction' => 'vertical', 'start' => 'white',       'end' => 'red'));   $Canvas->setLineColor('black');   $Canvas->addVertex(array('x' => 130, 'y' => 25));   $Canvas->addVertex(array('x' => 180, 'y' => 25));   $Canvas->addVertex(array('x' => 180, 'y' => 100));         $Canvas->polygon(array('connect' => true));   $Canvas->setFont(array(      'name' => 'Arial', 'size' => 12));   $Canvas->addText(array(      'x' => 140, 'y' => 105, 'text' => 'Polygon',      'color'=>'red'));      $Canvas->setLineColor('blue');   $Canvas->line(array(      'x0'=>10,'y0'=>140,'x1'=>190,'y1'=>140));   $Canvas->setFont(array(      'name' => 'Arial', 'size' => 12));   $Canvas->addText(array(      'x' => 90, 'y' => 145, 'text' => 'Line','color'=>'blue'));      $Canvas->image(array(      'x' => 398, 'y' => 298,       'filename' => './pear-icon.png',       'alignment' => array(         'horizontal' => 'right',          'vertical' => 'bottom')));      $Canvas->show();      ?>
Figure 8. Composite Image: This image shows a composited set of SVG graphs built with the PEAR::Image_Canvas library.

You can go well beyond basic shapes by combining various elements in documents. For example, Listing 4 contains code to draw an image (see Figure 8) that displays a set of diagrams (a smooth area graph, an area graph, a smooth line graph, a line graph, a bar graph, and an odo graph).

Creating Dynamic Graphs
You’re not limited to static graphs. For example, you can use AJAX with SVG and PHP to create graphs that update dynamically when data changes. Listing 5 shows the HTML for the page that displays the graph, while Listing 6 shows the PHP code, and Listing 7 shows the JavaScript. Here’s the SVG output:

Figure 9. Dynamic Graph: This SVG graph gets generated dynamically through AJAX and PHP.

The SVG shown above gets rendered as shown in Figure 9.SVG is an elegant method for implementing graphical content in your web applications. It gives your browser clients the ability to draw vector graphics that you can generate and modify dynamically from PHP and other languages. As you've seen, there are several different PHP packages available that provide SVG support. You'll have to experiment with them to determine the SVG pakage that corresponds most closely with your application's requirements.


Share the Post: