#!/usr/bin/perl # Example code for fetching performances from BellBoard via its API # Written by Richard Smith, 2015, and released into the public domain. use strict; use warnings; use LWP::UserAgent; use XML::LibXML; # Search parameters are the same as on the search page of BellBoard. # Try visiting https://bb.ringingworld.co.uk/search.php and using it # to get a working search. In this example we search for all peals # rung at St Magnus-the-Martyr in 2014. my $params = { 'place' => 'London', 'from' => '2014-01-01', 'to' => '2014-12-31', 'address' => 'Magnus', 'length' => 'peal' }; # Use the perl LWP::UserAgent library to fetch the data. (Your system may # have a separate package for the perl LWP::UserAgent library that needs # installing in addition to the main perl package. On Debian it is called # libwww-perl.) # # BellBoard API documentation: https://bb.ringingworld.co.uk/help/api.php # The export.php URL tells BellBoard to include details of the performances # instead of just a link which is what search.php provides. BellBoard # uses HTTP content negotiation to determine whether to send HTML or XML, # hence the 'Accept: application/xml' header. my $ua = new LWP::UserAgent( default_headers => new HTTP::Headers('Accept' => 'application/xml') ); my $uri = new URI( 'https://bb.ringingworld.co.uk/export.php' ); $uri->query_form(%$params); my $resp = $ua->get($uri); print "XML received from BellBoard\n"; print "---------------------------\n"; print $resp->content; print "---------------------------\n"; # Perl has various XML parsing libraries. Personally I like XML::LibXML, # which is built on top of the libxml2 C library. # http://search.cpan.org/~shlomif/XML-LibXML-2.0118/LibXML.pod # As with curl, you may need to install a separate package to get this # library. On Debian the package is called libxml-libxml-perl. my $doc = XML::LibXML->load_xml(string => $resp->content) or die("Unable to parse XML"); # XPath is a language for identifying parts of an XML document. # http://www.w3.org/TR/xpath/#location-paths gives some example XPath # expressions. As the the BellBoard XML format uses XML namespaces, we # need to register the namespace prefix. We associate it with the 'bb' # prefix, so to refer to a element, we write 'bb:performance'. my $xpath = new XML::LibXML::XPathContext($doc->documentElement); $xpath->registerNs('bb', 'http://bb.ringingworld.co.uk/NS/performances#'); my @perfs = $xpath->findnodes('bb:performance'); print "Found ".scalar(@perfs)." performances\n\n"; # Extract the date and method from each performance. We do this with an # XPath query with $p, the performance, as the context node (i.e. root). # The DOMXPath inferface returns a list of matching elements even though # we know only one element will be found. foreach my $p (@perfs) { my $date = $xpath->findvalue('bb:date', $p); my $meth = $xpath->findvalue('bb:title/bb:method', $p); print "$date\t$meth\n"; }