Search code examples
xmlperlpostcgixmlwriter

Outputting XML to a browser from a Perl CGI script?


I've got a perl CGI script running on an Apache server. The script is, among other things, supposed to display some XML that is generated from input. Using the XML::Writer module, I've created a string scalar containing the right XML, but I can't seem to figure out how to post it back to the browser. Currently my function looks like this:

sub display_xml {
    # input variables here
    my $output = '';
    my $writer = XML::Writer->new(
                   OUTPUT=>\$output,
                   DATA_MODE => 1,
                   DATA_INDENT =>1
    };
    $writer->xmlDecl('UTF-8');
    $writer->startTag('response');
    #omitted for brevity
    $writer->endTag('response');
    $writer->end();
}

Can anyone help me with this? Printing $output to STDOUT doesn't work, and I didn't see any functions in CGI.pm to do this (print $cgi->header('text/xml'); works, but I can't figure out how to print the body).


Solution

  • CGI is relatively simple protocol, that send standard output of your script to client machine. All you need is to put header at the start of the output. This works for me:

    use CGI qw(:standard);
    use XML::Writer;
    
    my $output = '';
    my $writer = XML::Writer->new(
        OUTPUT      => \$output,
        DATA_MODE   => 1,
        DATA_INDENT => 1
    );
    $writer->xmlDecl('UTF-8');
    $writer->startTag('response');
    
    #omitted for brevity
    $writer->endTag('response');
    $writer->end();
    
    print header('text/xml'), $output;
    

    Also make sure that you put shebang line at the start and make the script executable, so the server know how to run it:

    #!perl