To process JSON data with PHP, you can use the `json_decode()` function to convert the JSON string into a PHP variable. Here’s an example:
“`php
$json = ‘{“name”:”John”, “age”:30, “city”:”New York”}’;
$person = json_decode($json);
echo $person->name; // Output: John
echo $person->age; // Output: 30
echo $person->city; // Output: New York
“`
In this example, the JSON string contains information about a person – their name, age, and city. The `json_decode()` function converts this JSON string into a PHP object. You can then access the data using the object syntax (`$person->name`) to access specific properties.
You can also convert the JSON string into an associative array by passing `true` as the second parameter to the `json_decode()` function:
“`php
$json = ‘{“name”:”John”, “age”:30, “city”:”New York”}’;
$person = json_decode($json, true);
echo $person[‘name’]; // Output: John
echo $person[‘age’]; // Output: 30
echo $person[‘city’]; // Output: New York
“`
In this case, the JSON string is converted into an associative array, and you can use array syntax (`$person[‘name’]`) to access the data.
If you have multiple objects in your JSON string, you can use a loop to iterate over them:
“`php
$json = ‘[{“name”:”John”, “age”:30, “city”:”New York”},{“name”:”Jane”, “age”:25, “city”:”Los Angeles”}]’;
$people = json_decode($json);
foreach ($people as $person) {
echo $person->name . ‘, ‘ . $person->age . ‘, ‘ . $person->city . ‘
‘;
}
“`
In this example, the JSON string contains an array of two objects representing different people. The `foreach` loop iterates over each object and displays their information.
You can also use the `json_encode()` function to convert a PHP variable into a JSON string:
“`php
$person = array(
‘name’ => ‘John’,
‘age’ => 30,
‘city’ => ‘New York’
);
$json = json_encode($person);
echo $json; // Output: {“name”:”John”,”age”:30,”city”:”New York”}
“`
In this example, the associative array `$person` is converted into a JSON string using the `json_encode()` function.