Titles to XML

Discussion in 'PHP' started by Maraska, Sep 5, 2008.

  1. #1
    Hi,

    I am new at PHP. I want to convert .srt file (movie titles) to xml format.
    SRT example:
    ...
    
    42
    00:02:10,010 --> 00:02:12,320
    How can you flirt with me
    while ignoring your phone?
    
    43
    00:02:12,330 --> 00:02:14,230
    Well,I am a man of perspective.
    
    ...
    Code (markup):
    XML (possible output):
    
    ...
    
    <title id="42">
      <time start="00:02:12,330"  end="00:02:14,230">
      <text1><![CDATA[How can you flirt with me]]></text1>
      <text2><![CDATA[while ignoring your phone?]]></text2>
    </title>
    
    <title id="43">
      <time start="00:02:12,330"  end="00:02:14,230">
      <text1><![CDATA[Well,I am a man of perspective.]]></text1>
      <text2><![CDATA[]]></text2>
    </title>
    
    ...
    Code (markup):

    Is this possible? Where to start?

    Please help,
    Thank you!
     
    Maraska, Sep 5, 2008 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    function srt_to_xml($source, $target)
    {
    	if (!$srt_data = @file_get_contents($source))
    	{
    		trigger_error('Unable to open source .srt file', E_USER_WARNING);
    		return false;
    	}
    	else if (!$target_fp = @fopen($target, 'w'))
    	{
    		trigger_error('Unable to open/create target .xml file', E_USER_WARNING);
    		return false;
    	}
    	
    	$srt_data = str_replace("\r", null, trim($srt_data));
    	$sections = explode("\n\n", $srt_data);
    	
    	fwrite($target_fp, "<titles>\n");
    	
    	foreach ($sections AS $section)
    	{
    		$lines  = explode("\n", trim($section));
    		$xml    = '';
    		$amount = 0;		
    	
    		foreach ($lines AS $key => $line)
    		{
    			switch ($key)
    			{
    				case 0:
    					$xml .= "\t<title id=\"{$line}\">\n";
    					break;
    				case 1:
    					list($start, $end) = explode(' --> ', $line);
    					$xml .= "\t\t<time start=\"{$start}\" end=\"{$end}\" />\n";
    					break;
    				default:
    					$amount++;
    					$xml .= "\t\t<text{$amount}><![CDATA[{$line}]]></text{$amount}>\n";
    					break;
    			}
    		}
    		
    		fwrite($target_fp, "{$xml}\t</title>\n\n");
    		
    		$xml = '';
    		$amount = 0;
    	}
    	
    	fwrite($target_fp, "</titles>");	
    	@fclose($fp);
    	@fclose($target_fp);
    	
    	return true;
    }
    
    PHP:
    Usage example:
    
    $srt_file = 'titles.srt';
    $target_file = 'titles.xml';
    
    if (srt_to_xml($srt_file, $target_file))
    {
        echo 'XML file created.';
    }
    else
    {
        echo 'Error';
    }
    
    PHP:
     
    nico_swd, Sep 6, 2008 IP
  3. Maraska

    Maraska Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    WoW!!! Thank you so much!
     
    Maraska, Sep 6, 2008 IP