douan7601 2015-12-26 07:24
浏览 56
已采纳

无法使用PHP将远程mp3文件下载到服务器

I am trying to download a pronunciation file (approx. 8kb) to server using a server-side PHP. Taking cue from a number of threads discussing this issue, I tried the following:

$numwrd = str_word_count($wrd);
    if($numwrd == 1){
        $html = file_get_html("http://www.dictionaryapi.com/api/v1/references/spanish/xml/" . rawurlencode($wrd) . "?key=" . rawurlencode('6d4d41f9-c28f-4544-9bb3-1b4708d1a4d1'));
        $sn = $html->find('sound');
        if($sn[0] != ""){
            $foldername = findsub($sn[0]->plaintext);
            $filename = explode(".", $sn[0], 2)[0];
            $audiofn = $foldername . $filename . '.mp3';
            $soundurl = 'http://media.merriam-webster.com/audio/prons/es/me/mp3/' . $foldername . '/' . $filename . '.mp3';
            $path = 'amit.mp3';
            $headers = getHeaders($soundurl);
            if ($headers['http_code'] === 200 and $headers['download_content_length'] < 1024*1024) {
              if (download($url, $path)){
                return $audiofn . " " . $soundurl; 
              }
            }
        }
        else { return "not found"; }
    }
    else { return "not found"; }
function getHeaders($url)
{
  $ch = curl_init($url);
  curl_setopt( $ch, CURLOPT_NOBODY, true );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
  curl_setopt( $ch, CURLOPT_HEADER, false );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
  curl_setopt( $ch, CURLOPT_MAXREDIRS, 3 );
  curl_exec( $ch );
  $headers = curl_getinfo( $ch );
  curl_close( $ch );

  return $headers;
}
function download($url, $path)
{
  # open file to write
  $fp = fopen ($path, 'w+');
  # start curl
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  # set return transfer to false
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
  curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
  # increase timeout to download big file
  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
  # write data to local file
  curl_setopt( $ch, CURLOPT_FILE, $fp );
  # execute curl
  curl_exec( $ch );
  # close curl
  curl_close( $ch );
  # close local file
  fclose( $fp );

  if (filesize($path) > 0) return true;
}

This didn't work so I tried again with file_get_contents. This method however only creates the file but with zero bytes. The values in $foldername, $filename, $audiofn, and $soundurl are evaluating correctly and all these variables have been tested. I can manually download the file by browsing to the URL, right clicking in the browser, and clicking download file as.... What could be wrecking my PHP?

P.S.: I just tried a modified function using cURLand this failed too:

function down($url, $target){//feeding it $soundurl and $path values
    set_time_limit(0);
    $file = fopen(dirname(__FILE__) . $target, 'w+');
    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_BINARYTRANSFER => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FILE           => $file,
        CURLOPT_TIMEOUT        => 50,
        CURLOPT_USERAGENT      => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
    ]);
    $response = curl_exec($curl);

    if($response === false) {
        throw new \Exception('Curl error: ' . curl_error($curl));
    }
    $response;
}
  • 写回答

1条回答 默认 最新

  • dtrvzd1171 2015-12-26 18:04
    关注

    Finally got it to work! This is what fixed it (line 7):

    $filename = explode(".", $sn[0]->plaintext, 2)[0];
    

    The reason I had to add the ->plaintext attribute is because without it, the value being returned to $filename was an xml tag instead of the text inside of that tag. Since the following line of code takes this value as input, this was corrupting the URL being called for download:

    $soundurl = 'http://media.merriam-webster.com/audio/prons/es/me/mp3/' . $foldername . '/' . $filename . '.mp3';
    

    Now the file downloads successfully because the URL is being formed correctly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么