I’m just learning PERL. I’ve read some docs on parsing XML and reused some of my colleague’s code. But I can’t seem to get it to simply print out a list of the 3 football player names in this data. Please help. Here is the PERL code:
#! /usr/bin/perl -w
use strict;
use DBI;
use XML::Simple;
use LWP::UserAgent;
use HTTP::Request;
use Time::gmtime;
use Time::Local;
use Data::Dumper;
sub statsInit(){
my $xml_api_url = "http://myprovider.com/nfldata.xml";
my $xml = getXML($xml_api_url);
my $xmlData = xml2Simple($xml);
print "Hello World";
foreach my $player (@{$xmlData->{player}}){
my $playername = $player->{name};
print "pn = $playername | ";
}
}
sub getXML($){
my ($xmlURL) = @_;
my $dataresponse = '';
my $agent = LWP::UserAgent->new(env_proxy => 1, keep_alive => 1, timeout => 100);
my $header = HTTP::Request->new(GET => $xmlURL);
my $request = HTTP::Request->new('GET', $xmlURL, $header);
my $response = $agent->request($request);
if($response->is_success){
$dataresponse = $response->content(); #Loaded data from FINAL_XML
}
return $dataresponse;
}
sub xml2Simple(){
my ($xml) = @_;
my $xmlObj = XML::Simple->new(KeyAttr => {});
my $xmlData = '';
my $parsedData = '';
if($xml){
$xmlData = $xmlObj->XMLin($xml);
}
return $xmlData;
}
statsInit();
-------- NOW BELOW IS THE RETRIEVED XML DATA --------
<season xmlns="http://myprovider.com/schema/nfl/statistics-v1.0.xsd" season="2012" season_type="REG">
<team id="BUF" name="Bills" market="Buffalo">
<players>
<player id="100" name="Nick Barnett" games_played="1" games_started="1" jersey="50" position="OLB">
<defense tackle="7" ast="2" />
</player>
<player id="101" name="Ryan Fitzpatrick" games_played="1" games_started="1" jersey="14" position="QB">
<rushing att="2" yds="8" />
<passing att="32" cmp="18" yds="195" td="3" int="3"/>
</player>
<player id="102" name="Fred Jackson" games_played="1" games_started="1" jersey="22" position="RB">
<rushing att="6" yds="15" td="0"/>
</player>
</players>
</team>
</season>
So my code seems to retrieve the data ok, and I get no errors. “Hello World” gets printed. But it never goes into the players loop and doesn’t print any player names. What am I doing wrong?
I figured it out. I guess I had to change this line.
to this: