Code Snippets/Examples

Here are some examples/snippets to keep you moving on your projects or just to peak your interest.

Recursive Directory Iteration

So, you want to traverse a directory (and its subdirectories) in PHP5, huh? This should work for you.

<?php

$dir="/var/www/html/mysite/";

$rdi = new RecursiveDirectoryIterator("$dir");
foreach(new RecursiveIteratorIterator($rdi) as $f) {
   echo "$f -- {$f->getMTime()}\n";
   echo "$f -- {$f->getPathInfo()}\n";
}

/***
 * $f is an object of type SplFileInfo
 * @see http://www.php.net/~helly/php/ext/spl/classSplFileInfo.html
 ***/

?>

If you just want a single directory without children, try this:

Non-Recursive Directory Iteration

<?php

$dir="/var/www/html/mysite/";

$di = new DirectoryIterator( $dir );
foreach($di as $d ) {
    if (!$d->isDot()) {
        echo $d."\n";
    }
}

/***
 * @see http://us3.php.net/manual/en/class.directoryiterator.php
 ***/

?>

SimpleXML and NameSpaces

Namespaces are a PITA. However, if you know the document you are parsing, they aren't so bad.

<?php

$simple = simplexml_load_file('http://rss.news.yahoo.com/rss/topstories');

foreach ($simple->channel->item as $i) {
#   print_r($i);
    $my_media=array_shift($i->xpath('.//foo:my_media));
    print_r($my_media);
}

?>

HTTP Status Codes

Short and Sweet - thanks Squid! - http://www.comfsm.fm/computing/squid/FAQ-6.html#ss6.8

XARGS Fun

  • # -J _REPLACE_ lets you position where the args go
    ls |xargs -J _REPLACE_ -n 5 ./repeat _REPLACE_ foo
     
  • # -n structures how many to send to the command
    ls |xargs -n 5
     
  • # logging - send the command and args to be run:
    ls |xargs -t -n 10 ./repeat 2 > xargs.log
     
  • # limit args sent to command by bytes (command won't run if data exceeds the '-s' value of 2)
    poodlespring-lm:~ supertom$ ls | xargs -s 2 -t ./repeat 
    xargs: insufficient space for command

    Back to Code