Open In App

How to Convert a String to JSON Object in PHP ?

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

Given a String, the task is to convert the given string into a JSON object in PHP. JSON (JavaScript Object Notation) is a widely used data interchange format. PHP provides convenient functions to work with JSON data.

Approach 1: Using json_decode() to Convert to an Array

The json_decode() function is a versatile and commonly used method to convert a JSON-formatted string into a PHP object.

PHP




<?php
  
// Your JSON-formatted string
$jsonString = '{"key1": "value1", "key2": "value2", "key3": "value3"}';
  
// Convert JSON string to a PHP object
$phpObject = json_decode($jsonString);
  
// Output the result
print_r($phpObject);
?>


Output

stdClass Object
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
)

Approach 2: Handling Errors with json_last_error() and json_last_error_msg() Methods

It’s essential to handle errors that may occur during the decoding process. The json_last_error() function returns the last error occurred, and json_last_error_msg() provides a human-readable error message.

PHP




<?php
  
$jsonString = '{"key1": "value1", "key2": "value2", "key3": "value3"}';
  
// Decode the JSON string
$decodedData = json_decode($jsonString);
  
// Check for errors
if ($decodedData === null) {
    echo "Error decoding JSON: " 
        . json_last_error_msg();
} else {
      
    // Successfully decoded
    print_r($decodedData);
}
  
?>


Output

stdClass Object
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads