2016-03-31 62 views
0

我想將音頻播放器添加到Magento商店的產品查看頁面以播放示例音頻文件,因此我編輯了magento_root/app/design/path/to/theme/template/downloadable/catalog/product/samples.phtml如何從類似MVC的URL中確定文件類型

<?php if ($this->hasSamples()): ?> 
<dl class="item-options"> 
    <dt><?php echo $this->getSamplesTitle() ?></dt> 
    <?php $_samples = $this->getSamples() ?> 
    <?php foreach ($_samples as $_sample): ?> 
     <dd> 
      <!--HTML5 Audio player--> 
      <audio controls> 
       <source src="<?php echo $this->getSampleUrl($_sample) ?>" type="audio/mpeg"> 
       Your browser does not support the audio element. 
      </audio> 
      <br/> 
      <a href="<?php echo $this->getSampleUrl($_sample) ?>" <?php echo $this->getIsOpenInNewWindow() ? 'onclick="this.target=\'_blank\'"' : ''; ?>><?php echo $this->escapeHtml($_sample->getTitle()); ?></a> 
     </dd> 
    <?php endforeach; ?> 
    </dl> 
<?php endif; ?> 

這工作正常,但我希望播放器只顯示音頻文件。我的問題是,由$this->getSampleUrl($_sample)返回的網址格式爲 http://example.com/index.php/downloadable/download/sample/sample_id/1/,但沒有關於網址上的文件類型的信息。

我認爲抓取URL的內容來確定文件類型,但我覺得完全讀取文件以確定文件類型是愚蠢的。 試過pathinfo()但它沒有返回任何有關文件類型。

我想要實現這樣的

$sample_file = $this->getSampleUrl($_sample); 
$type = getFileType($sample_file); 
if(preg_match('audio-file-type-pattern',$type){ ?> 
<!--HTML5 Audio player--> 
<audio controls> 
    <source src="<?php echo $sample_file ?>" type="<?php echo $type?>"> 
    Your browser does not support the audio element. 
</audio> 
} 

回答

2

你可以嘗試發送帶有捲曲HEAD請求。隨着HEAD請求您是剛開始的頭,而不是體(在你的情況下,音頻文件):

<?php 

$url = 'http://domain.com/index.php/downloadable/download/sample/sample_id/1/'; 

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); 

// Only calling the head 
curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output 
curl_setopt($ch, CURLOPT_NOBODY, true); 


$content = curl_exec ($ch); 
curl_close ($ch); 


echo $content; 

//Outputs: 
HTTP/1.1 200 OK 
Date: Fri, 01 Apr 2016 16:56:42 GMT 
Server: Apache/2.4.12 
Last-Modified: Wed, 07 Oct 2015 18:23:27 GMT 
ETag: "8d416d3-8b77a-52187d7bc49d1" 
Accept-Ranges: bytes 
Content-Length: 571258 
Content-Type: audio/mpeg 

用一個簡單的正則表達式就可以得到該文件的Content-Type:

preg_match('/Content\-Type: ([\w\/]+)/', $content, $m); 

echo print_r($m,1); 

//Outputs: 
Array 
(
    [0] => Content-Type: audio/mpeg 
    [1] => audio/mpeg 
)