简体   繁体   中英

Save byte array to a file PHP

I have not been able to find a solution using PHP. Basically, when a user clicks on the "download PDF" link, It will call a PHP function that takes a byte array and parses it as a PDF. I dont know how to go about it. Any help would be great!

EDIT: I'm getting the "byte array" like this:

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

The "$result" is supposedly the byte array that looks like this:

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

..etc. Basically I need to take what im getting back and save it as a PDF (or any generic file for the matter).

You can try something like this:

// 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's answer will work, but will take very long for large files. I would recommend doing the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM