How to Convert Byte Array to JSON in PHP ?
Last Updated :
05 Jan, 2024
Given a Byte Array, the task is to convert Byte Array into JSON using PHP. Converting a byte array to JSON in PHP is a common task, especially when dealing with binary data or when you want to represent raw data in a JSON format.
One common approach is to encode the byte array as a base64 string and then include it in a JSON structure. This method ensures that binary data is properly represented in a JSON-compatible format.
PHP
<?php
$byteArray = [0x71, 0x101, 0x101, 0x107, 0x115];
$base64String = base64_encode (pack( 'C*' , ... $byteArray ));
$jsonData = json_encode([ 'data' => $base64String ]);
echo $jsonData ;
?>
|
Output
{"data":"cQEBBxU="}
Approach 2: Using Custom Conversion Function
You can create a custom function to convert a byte array to a hexadecimal or binary string and then include it in a JSON structure.
PHP
<?php
$byteArray = [71, 101, 101, 107, 115];
function byteArrayToHex( $byteArray ) {
return implode( '' , array_map ( 'dechex' , $byteArray ));
}
$hexString = byteArrayToHex( $byteArray );
$jsonData = json_encode([ 'data' => $hexString ]);
echo $jsonData ;
?>
|
Output
{"data":"4765656b73"}
Share your thoughts in the comments
Please Login to comment...