Search code examples
phpjpgraph

How to embed a graph (jpgraph) in a web-page


I am using this script which is one of the examples provided by jpgraph itself. When I put this on a web-page (blank) by itself, it's drawing the graph. But when I embed the code in already existing web-page (with some content), it ain't drawing a graph.

GD is already enabled according to phpinfo(). Iam using jpgraph 3.5.0b1.


Solution

  • The problem is that you are mixing HTML/text output with image output.

    Any time you have a PHP script generate graphical content you have to handle the output differently than normal HTML or text.

    There are a few routes, I'll cover them briefly here.

    Save the output to a file and use that filename in your HTML

    //replace this line:
    // Display the graph
    //$graph->Stroke();
    
    // with these lines:
    
        // Default is PNG so use ".png" as suffix
        $fileName = "/tmp/imagefile.png";
        $graph->img->Stream($fileName);
    

    .. then use $filename in an image tag, like this (for example):

    print '<img src="'.$filename.'" />';

    Create a standalone PHP script that will output the graphic

    You can use the example script as-is, alone in a file called graph_render_script.php. Then, in your HTML, you use that script as a source:

    <img src="graph_render_script.php" />
    

    Output base-64 encoded data

    Another route is to use base-64 encoded image data. This is relatively simple to do:

    print '<img src="data:image/png;base64,'.base64_encode($graph->Stroke()).'" />';

    As always, the documentation should be your guide!

    Documentation