Importing programmatically into Blubrry Podcasting from xml feed

During the conversion of an old PERL website into wordpress, I chose to use the very nice plugin Blubrry Powerpress Podcasting to display the podcasts. The feed having more than 300 episodes, there were no way I would import all of them manually. After a bit of tinkering, here is a solution to parse an itunes xml feed and import it programmatically into Blubrry Podcasting plugin:

function import_podcasts(){
   
    //$itunes_feed = "http://mysite.com/podcast/feed.dtd"; //if your feed is remote

    $itunes_feed = file_get_contents('feed.dtd.xml'); //if it is local

    $itunes_feed = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $itunes_feed);

    $itunes_xml = new SimpleXMLElement($itunes_feed);
   
    $channel = $itunes_xml->channel;

    $itunes_entry = $channel->item;

    foreach($itunes_entry as $entry){

        $title = (string) $entry->title;
        $author = (string) $entry->itunesauthor;
        $content = (string) $entry->itunessummary;
        $mediaUrl = (string) $entry->guid;
        $duration = (string) $entry->itunesduration;
        $date = $entry->pubDate;
        $date = date('Y-m-d H:i:s', strtotime($date));
        $tags = (string) $entry->ituneskeywords; //explode(' ', $entry->ituneskeywords);
        $mediaSize = (string) $entry->enclosure->attributes()->length;
        $mediaType = (string) $entry->enclosure->attributes()->type;
        $image = null;
       
        //Episode Number
        $path = parse_url($mediaUrl,PHP_URL_PATH);
        $path = trim($path,'/');
        $dir = pathinfo($path,PATHINFO_DIRNAME);
        $episodeNum = pathinfo($path,PATHINFO_FILENAME);
       
        //Insert POST
        $post = array(
            'post_type'    => 'post',
            'post_status'   => 'publish',
            'post_title'    => 'Podcast '.$episodeNum.' - '.$title,
            'post_content'    => $content,         
            'tags_input'   => str_replace(' ',',',$tags),
            'post_date'      => $date
        );
        $post_id = wp_insert_post($post); //return the post id
       
        $cat_id = get_page_category('Podcast');
        wp_set_post_terms($post_id, $cat_id, 'category', false );
       
        //Add POST META (serialize the data)
        $EnclosureData = trim($mediaUrl) . "\n" . trim($mediaSize) . "\n". trim($mediaType);
               $Serialized = array();
               if( !empty($duration) )
                  $Serialized['duration'] = $duration;
               if( !empty($image) )
                  $Serialized['image'] = $EpisodeData['image'];
               
               if( count($Serialized) > 0 )
                  $EnclosureData .= "\n".serialize($Serialized);
       
       
        add_post_meta($post_id, 'enclosure', $EnclosureData, true);
        echo 'Post '.$post_id.' imported \n';

    }
   
}