从url数组下载mp3到zip文件

时间:2015-05-05 00:47:18

标签: php download zip mp3

我有一系列指向mp3文件的链接。我需要从服务器下载所有mp3,然后压缩。

以下代码无效:

有什么建议吗?

 class Program
{
    static void Main(string[] args)
    {
        using(var db= new AW())
        {
            var e = db.Employees.First();
            e.JobTitle = "Web Developper";
            db.SaveChanges();
        }
    }
}
  

存档格式未知或已损坏

2 个答案:

答案 0 :(得分:1)

首先需要下载这些文件并将它们本地存储在您的服务器上。完成后,您将能够压缩它们并使zip文件可供下载。

实现此目标的最基本方法是使用PHP的file_get_contents()file_put_contents()parse_url()

此代码尚未经过全面测试。

// Fixed the name of the array
$audio_files = array('http://example.com/1.mp3', 'http://example.com/2.mp3');

// You need to change this to 
// a path where you want to store your 
// audio files (Absolute path is best)
$local_path = '/local/path/here/';
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

// Download the files
// Not an elegant way to 
// download files
foreach ($audio_files as $file) {
    // First let's get the file name
    // by parsing the URL
    // and trimming the '/'
    $file_name = ltrim(parse_url($file, PHP_URL_PATH), '\/');

    // Download the file
    $a_contents = file_get_contents($file);

    // Place the downloaded content
    // in the defined local path
    file_put_contents($local_path . $file_name, $a_contents);

    // Add the file to archive
    $zip->addFile($local_path . $file_name);
}

$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

由于以下原因(其他许多原因),这是实现任务的非常糟糕的方法

  1. 下载过程没有超时
  2. 如果文件无法下载,则会暂停执行
  3. 可能需要很长时间(取决于音频文件的大小)来提供zip文件
  4. 没有正确的错误/异常处理程序
  5. 关于结构的许多其他原因我不会在这里经历。

答案 1 :(得分:-1)

尝试以下操作:使用parse_url获取实际文件名,使用file_get_contents和file_put_contents下载并在本地保存数据...

$audio_flies = array('http://example.com/1.mp3','http://example.com/2.mp3');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($audio_files as $file) {
  echo "$file";
  $parsed = parse_url($file); 
  $localfile = "." . $parsed["path"];
  $mp3 = get_file_contents($file);
  file_file_contents($localfile, $mp3);
  $zip->addFile($localfile);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
相关问题