Outputting XML to a browser from a Perl CGI script?
I've got a perl CGI script running on an Apache server. The s开发者_如何转开发cript 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).
You can do it without using CGI actually.
print "Content-Type: text/xml\r\n"; # header tells client you send XML
print "\r\n"; # empty line is required between headers
# and body
print $output; # the body: XML
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
精彩评论