2013-10-01 52 views
0

我有一個22M的docx文件,並希望在php中使用base64_encode()函數進行編碼。但運行此函數後總是返回NULL值。是否有此功能的限制文件大小或條件。我的代碼:爲什麼base64_encode()返回null

$handle = fopen($fullpathfile, "rb"); 
$imagestr = base64_encode(fread($handle, filesize($fullpathfile))); 
fclose($handle); 
+1

什麼FREAD回報?你知道嗎,這是docx文件,還是你真的測試過它? – GolezTrol

+5

[''base64_encode'](http://php.net/base64_encode)永遠不會返回'null'。但是,它在失敗時返回「false」。 – Gumbo

+0

22M是大文件,也許你正在某處「內存不足」。 –

回答

0

試試這個代碼

$fh = fopen($fullpathfile, 'rb'); 


$cache = ''; 
$eof = false; 

while (1) { 

    if (!$eof) { 
     if (!feof($fh)) { 
      $row = fgets($fh, 4096); 
     } else { 
      $row = ''; 
      $eof = true; 
     } 
    } 

    if ($cache !== '') 
     $row = $cache.$row; 
    elseif ($eof) 
     break; 

    $b64 = base64_encode($row); 
    $put = ''; 

    if (strlen($b64) < 76) { 
     if ($eof) { 
      $put = $b64."\n"; 
      $cache = ''; 
     } else { 
      $cache = $row; 
     } 

    } elseif (strlen($b64) > 76) { 
     do { 
      $put .= substr($b64, 0, 76)."\n"; 
      $b64 = substr($b64, 76); 
     } while (strlen($b64) > 76); 

     $cache = base64_decode($b64); 

    } else { 
     if (!$eof && $b64{75} == '=') { 
      $cache = $row; 
     } else { 
      $put = $b64."\n"; 
      $cache = ''; 
     } 
    } 

    if ($put !== '') { 
     echo $put; 

    } 
} 


fclose($fh); 
+0

請在代碼中提供註釋以解釋這是如何工作的:) – Martijn

+0

爲什麼不簡單地每次迭代讀取最多57個字節? – Gumbo