簡體   English   中英

將字節數組保存到文件 PHP

[英]Save byte array to a file PHP

我一直無法找到使用 PHP 的解決方案。 基本上,當用戶單擊“下載 PDF”鏈接時,它會調用一個 PHP 函數,該函數接受一個字節數組並將其解析為 PDF。 我不知道該怎么做。 任何幫助都會很棒!

編輯:我得到這樣的“字節數組”:

<?php
$userPDF = $_POST['username'];
$passPDF = $_POST['password'];
$idPDF = 'MO-N007175A';
//PDF Function
$data = array("id" => $idPDF, "username" => $userPDF, "password" => $passPDF);                                                                    
$data_string = json_encode($data);                                                
$ch = curl_init('http://*****.com/****/v1/DealPdf');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                 
curl_setopt($ch, CURLOPT_VERBOSE, 1 );                                                                  
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json')                                                                       
);                                                                                                                   
$result = curl_exec($ch);
var_dump($result);
?>

“$result”應該是看起來像這樣的字節數組:

string(1053240) "[37,80,68,70,45,49,46,54,10,37,211,244,204,225,10,49,32,48,32,111,98

..等等。 基本上我需要把我得到的東西保存為PDF(或任何通用文件)。

你可以嘗試這樣的事情:

// suppose that the response is a JSON array (look like it)
$bytes = json_decode($results);

$fp = fopen('myfile.pdf', 'wb+');

while(!empty($bytes)) {
    $byte1 = array_shift($bytes);
    $byte2 = array_shift($bytes);
    if(!$byte2) {
      $byte2 = 0;
    }

    fwrite($fp, pack("n*", ($byte1 << 8) + $byte2); // big endian byte order ?
}

fclose($fp);

GiDo的答案會起作用,但對於大文件需要很長時間。 我建議執行以下操作:

$bytes = json_decode($results);
$bytesStr = pack('C*', ...$bytes);
file_put_contents('myfile.pdf', $bytesStr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM