将字节数组保存到PHP文件中

时间:2012-03-08 16:06:24

标签: php pdf bytearray

我无法使用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(或任何通用文件)。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

// 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);

答案 1 :(得分:0)

GiDo的答案会起作用,但大文件将花费很长时间。我建议您执行以下操作:

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