Parsing XML Data
You can use many tools to parse XML data sent to a hook script. However, the main two that are discussed here are
XML::Simple for Perl and
SimpleXML for PHP.
Both of these tools operate similarly, converting XML into hashes (Perl) or associative arrays (PHP) that allow you to directly manipulate data within the scripts.
PHP SimpleXML
In order to create a SimpleXML object in PHP, you must call
simplexml_load_string() and assign its
return output to a value.
$xml_string = "<xml><CPDATA><user>someusername</user></CPDATA></xml>";
$xml_object = simplexml_load_string($xml_string);
var_dump($xml_object);
This will transform the provided XML into a SimpleXML object. SimpleXML objects are similar to associative arrays. The code in the example above should produce output similar to:
object(SimpleXMLElement)#1 (1) {
["CPDATA"]=>
object(SimpleXMLElement)#2 (1) {
["user"]=>
string(12) "someusername"
}
}
Any data contained within this object can be accessed by treating each container as an associative. This means that if you would like to print data contained within the
<user> tag, you would need to call the following element of the object:
$xml_object->CPDATA->user;
Perl XML::Simple
In order to work with XML in Perl, you will need to load the
XML::Simple Perl module using the following command:
Use XML::Simple
Once the module has been loaded, several functions will also be loaded automatically. One of these functions is called
XMLin. Using this function, you can translate XML data into Perl hash references.
use XML::Simple;
use Data::Dumper;
my $xml_string = "<xml><CPDATA><user>someusername</user></CPDATA></xml>";
my $xml_hashref = XMLin($xml_string);
print Dumper $xml_hashref
This will return the following output:
$VAR1 = {
'CPDATA' => {
'user' => 'someusername'
}
};
In order to access this data, you will need to call each key in the hash reference as it corresponds to the container in the XML data, like so:
$xml_hashref->{'CPDATA'}->{'user'};