How to usebase64_encode() and json_encode() Functions in PHP

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="}

How to Convert Byte Array to JSON in PHP ?

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.

Table of Content

  • Using base64_encode() and json_encode() Functions
  • Using Custom Conversion Function

Similar Reads

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....

Approach 2: Using Custom Conversion Function

...