How to convert a string to JSON object in PHP

To convert a string to a JSON object in PHP, you can use the json_decode function. This function takes a JSON string as its input and returns a PHP object or associative array with the same data.

Here is an example of how you can use json_decode to convert a JSON string to an object:

<?php

$json = '{"name":"John", "age":30, "city":"New York"}';

// decode the JSON data into a PHP object
$obj = json_decode($json);

// access the object properties
echo $obj->name . PHP_EOL;  // John
echo $obj->age . PHP_EOL;   // 30
echo $obj->city;  // New York

Watch a course Learn object oriented PHP

You can also pass a second argument to json_decode to convert the JSON string into an associative array:

<?php

$json = '{"name":"John", "age":30, "city":"New York"}';

// decode the JSON data into an associative array
$array = json_decode($json, true);

// access the array elements
echo $array['name'] . PHP_EOL;  // John
echo $array['age'] . PHP_EOL;   // 30
echo $array['city'];  // New York