Jul 24, 2011

M3U file editor

M3U are playlist files. I have developed this simple editor for a friend, that needed to edit IPTv playlist files.

The editor includes mass (bulk) edits as well as item editor. You can upload and export the same filetype.

You can check out the editor here:
http://kafol.net/code/m3u-edit/

M3U files are easy to parse:
<?
class m3u {
 public $data = array();
 public $name = '';
 
 public function __construct($data = null) {
  if(!is_null($data)) {
   $this->load($data);
  }
 }
 
 public function load($data) {
  if(!is_array($data)) explode("\n",$data);
  
  foreach($data as $i=>$line) {
   if(preg_match('/^#EXTNAME:(.+)/is',$line,$m)) {
    $this->name = clean($m[1]);
   }
   if(preg_match('/^#EXTINF:(\d+),(.+)/is',$line,$m)) {
    $item = new m3uitem();
    $item->length = intval($m[1]);
    $item->setName($m[2]);
    if(preg_match('/^#EXTTV:(.+)/is',$data[$i+1],$m)) {
     $item->setCategories($m[1]);
    }
    $item->file = trim($data[$i+2]);
    $this->data[] = $item;
   }
  }
 }
 
 public function sort() {
  usort($this->data, array(__CLASS__,'cmp'));
 }
 
 public static function cmp($a,$b) {
  if($a->sort == $b->sort) {
   return 0;
  }
  return ($a->sort > $b->sort) ? +1 : -1;
 }
 
 public function export() {
  $r = "#EXTM3U\n#EXTNAME:{$this->name}\n\n";
  foreach($this->data as $d) {
   $r .= "#EXTINF:{$d->length},{$d->getName()}\n";
   if($d->getCategories() != '') {
    $r .= "#EXTTV:{$d->getCategories()}\n";
   }
   $r .= "{$d->file}\n\n";
  }
  return $r;
 }
 
}

class m3uitem {
 public $sort = 0;
 public $length = 0;
 public $file = '';
 private $name = '';
 private $categories = array();
 
 public function __construct() {}
 
 public function getName() { 
  return $this->name; 
 }
 
 public function setName($name) {
  $this->name = clean($name);
 }
 
 public function getCategories() {
  return implode(';',$this->categories);
 }
 
 public function setCategories($data) {
  $this->categories = is_array($data) ? $data : explode(';',clean($data));
  
  foreach($this->categories as $i=>$cat) {
   if(empty($cat)) {
    unset($this->categories[$i]);
   } else {
    $this->categories[$i] = clean($this->categories[$i]);
   }
  }
 }
}
?>


1 comment:

alfil said...

Hello
I would like to make for friends the same editor, but in the following format: http://borpas.info/iptvplayer-docs#16

If you can share your project, I guarantee to provide for you all my changes.