Open In App

How to Convert Byte Array to JSON in PHP ?

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Approach 1: Using base64_encode() and json_encode() Functions

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
  
// Byte Array
$byteArray = [0x71, 0x101, 0x101, 0x107, 0x115];
  
// Convert byte array to base64
$base64String = base64_encode(pack('C*', ...$byteArray));
  
// Create a JSON structure
$jsonData = json_encode(['data' => $base64String]);
  
// Display the result
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
  
// Byte Array
$byteArray = [71, 101, 101, 107, 115];
  
// Custom function to convert byte
// array to hexadecimal string
function byteArrayToHex($byteArray) {
    return implode('', array_map('dechex', $byteArray));
}
  
// Convert byte array to hexadecimal
$hexString = byteArrayToHex($byteArray);
  
// Create a JSON structure
$jsonData = json_encode(['data' => $hexString]);
  
// Display the result
echo $jsonData;
  
?>


Output

{"data":"4765656b73"}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads