A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label namespaces. Show all posts
Showing posts with label namespaces. Show all posts

Parse XML in PHP

http://php.net/manual/en/function.file-get-contents.php - fetch URL
http://php.net/manual/en/simplexmlelement.xpath.php - parse XML
http://www.php.net/manual/en/simplexml.examples-basic.php - register namespaces, etc.

Example for Google calendar. Most important parts are the namespaces and (string) casting.

    $contents = file_get_contents($calendar_url); // should end with 'full', not 'basic'
    $xml = new SimpleXMLElement($contents);

    $namespaces = $xml->getDocNamespaces();
    $xml->registerXPathNamespace('__empty_ns', $namespaces['']);
    $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005'); # xmlns:gd='http://schemas.google.com/g/2005'

    $entries = $xml->xpath("//__empty_ns:entry");
    while(list( , $node) = each($entries)) {
        $time_nodes = $node->xpath("gd:when/@startTime");
        while ($time_node = each($time_nodes)) {
            # <gd:when endTime="2011-08-19T17:00:00.000+01:00" startTime="2011-08-19T14:00:00.000+01:00"></gd:when>

            $time_text = (string)$time_node[1]->startTime;

            die "time = $time_text\n";

Perl subroutine parameters

Call subs like this:
sub_name(
      param1 => 'value1',
      param2 => 'value2',
);

Define subs like this:
sub sub_name {
    my $p1      = {@_}->{param1};
    my $p2      = {@_}->{param2};
    # etc
}

Importing a module's namespace in Perl

Ever get this error for a module you've written?

Use of inherited AUTOLOAD for non-method X() is deprecated

Put this at the top of your module:

package My::Module;

use Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(put the methods here);

And then in the main program:

use My::Module qw( the methods to import );

keywords: export import exporting