PHP script for downloading MP4 files from iPlayer

Paul Battley wrote a Ruby script to get around the BBC's continued attempts to stop people downloading MP4 files from iPlayer. Here's a version in PHP using libcurl:
$ch = curl_init();
// fetch the HTML and extract the PID
curl_setopt_array($ch, array(
  CURLOPT_URL => $argv[1], // URL of the iPlayer viewing page
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_FOLLOWLOCATION => TRUE,
  CURLOPT_USERAGENT => 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3',
  CURLOPT_COOKIEJAR => '/tmp/cookies.txt',
));
$html = curl_exec($ch);
if (! preg_match("/\bpid\s+:\s+'(.+?)'/", $html, $matches)) exit('No PID');
$pid = $matches[1];
// extract the title + episode
if (preg_match("/iplayer.pid\s+=\s+'(.+?)'/", $html, $matches)){	
  $xml = simplexml_load_file("http://www.bbc.co.uk/iplayer/metafiles/episode/{$matches[1]}.xml");
  $title = (string) $xml->concept->title;
  if ($xml->concept->subtitle)
    $title .= ' - ' . $xml->concept->subtitle;
  $title = preg_replace('/[^a-z0-9 \-]/i', '', $title);
}
if (!$title) $title = 'Untitled';
// fetch the content range value
curl_setopt_array($ch, array(
  CURLOPT_URL => "http://www.bbc.co.uk/mediaselector/3/auth/iplayer_streaming_http_mp4/$pid?" . rand(0, 1000000),
  CURLOPT_USERAGENT => 'Apple iPhone v1.1.4 CoreMedia v1.0.0.4A102',
  CURLOPT_RANGE => '0-1',
  CURLOPT_HEADER => TRUE,
));
$response = curl_exec($ch);
if (! preg_match('/\bContent-Range: bytes 0-1\/(\d+)/', $response, $matches)) exit ('No Content-Range');
// fetch the movie file
$out = fopen("$title.mov", 'w');
curl_setopt_array($ch, array(
  CURLOPT_RANGE => '0-' . $matches[1],
  CURLOPT_HEADER => FALSE,
  CURLOPT_NOPROGRESS => FALSE,
  CURLOPT_RETURNTRANSFER => FALSE,
  CURLOPT_FILE => $out,
));
curl_exec($ch);
curl_close($ch);