To process JSON data with PHP, you can use the `json_decode()` function to convert the JSON data into a PHP array or object. Here’s an example:
“`php
$jsonData = ‘{
“name”: “John Doe”,
“age”: 30,
“city”: “New York”
}’;
// Convert JSON data to PHP array
$data = json_decode($jsonData, true);
// Access the data
$name = $data[‘name’];
$age = $data[‘age’];
$city = $data[‘city’];
echo “Name: $name\n”;
echo “Age: $age\n”;
echo “City: $city\n”;
“`
This will output:
“`
Name: John Doe
Age: 30
City: New York
“`
If you want to convert the JSON data into a PHP object instead of an array, you can omit the second parameter of `json_decode()`:
“`php
$data = json_decode($jsonData);
// Access the data
$name = $data->name;
$age = $data->age;
$city = $data->city;
echo “Name: $name\n”;
echo “Age: $age\n”;
echo “City: $city\n”;
“`
The output will be the same as before.
If the JSON data contains nested structures, you can access them using the `->` operator for objects or `[‘key’]` for arrays. For example:
“`php
$jsonData = ‘{
“name”: “John Doe”,
“age”: 30,
“city”: “New York”,
“address”: {
“street”: “123 Main St”,
“zip”: “10001”
}
}’;
$data = json_decode($jsonData);
// Access the nested data
$street = $data->address->street;
$zip = $data->address->zip;
echo “Street: $street\n”;
echo “ZIP: $zip\n”;
“`
This will output:
“`
Street: 123 Main St
ZIP: 10001
“`
You can also use `json_decode()` to convert JSON data from a file. Just pass the file contents to the function instead of a JSON string:
“`php
$jsonData = file_get_contents(‘data.json’);
$data = json_decode($jsonData, true);
// …
“`
Note that `json_decode()` returns `null` if the JSON data is invalid. You can use the `json_last_error()` function to check if there was an error during decoding.