Ed9c50a6db8b5e078b5ef84306a8477c

Given an RSS feed and an output directory, this should download all the audio files from the feed into that directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
if (count($argv) != 3)
	die("Usage: $argv[0] <RSS feed URL> <output dir>\n");	

$rss = simplexml_load_file($argv[1]);
$rss->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');

$media = $rss->xpath("//item/media:content[@type='audio/mpeg']");
if (empty($media)){
	$media = $rss->xpath("//item/enclosure[@type='audio/mpeg']");
	if (empty($media))
		die("No media files found\n");
}

$curl = curl_multi_init();
$connections = array();
$files = array();

foreach ($media as $enclosure){
  $url = (string) $enclosure['url'];
  $md5 = md5($url);
  
  print "$url\n";
  
  $file = $argv[2] . "/$md5.mp3";
  if (file_exists($file)) continue;
  
  $files[$md5] = fopen($file, 'w');
  
  $connections[$md5] = curl_init();
  curl_setopt_array($connections[$md5], array(
    CURLOPT_URL => $url,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 3,
    CURLOPT_FILE => $files[$md5],
  	));
  	
  curl_multi_add_handle($curl, $connections[$md5]);
}

print "Downloading...";

$running = NULL;
do {
   curl_multi_exec($curl, $running);
   sleep(1);
} while ($running > 0);

foreach ($connections as $md5 => $connection){
  if ($data = curl_multi_getcontent($connection))
    file_put_contents($files[$md5], $data);
    
  curl_multi_remove_handle($curl, $connection);
  fclose($files[$md5]);
}

curl_multi_close($curl);

print "finished.\n";

Refactorings

No refactoring yet !

Your refactoring





Format Copy from initial code

or Cancel