How can I convert the given code/text into PHP? What would be the PHP syntax of it? There are like some arrays and some objects like items. I would like to restructure it into PHP and be able to convert back to it’s original format if necessary.
{
"status": "Pending",
"client": "John",
"invoice": {
"series": "INV",
"currency": "EUR",
"total": 20,
"items": [
{
"id": 5478,
"name": "Adapter Lenovo",
"amount": 1,
"cost": 10,
}
]
},
"parcels": [
{
"quantity": "1",
"weight": 2000
}
],
"sender": {
"company": "string",
"address": {
"city": "Tallin",
"street": "New Street"
}
},
"recipient": {
"name": "Peter",
"phone": 30258554455
}
}
>Solution :
You can convert the string into a an array or object using json_decode()
$json_string = '{
"status": "Pending",
"client": "John",
"invoice": {
"series": "INV",
"currency": "EUR",
"total": 20,
"items": [
{
"id": 5478,
"name": "Adapter Lenovo",
"amount": 1,
"cost": 10
}
]
},
"parcels": [
{
"quantity": "1",
"weight": 2000
}
],
"sender": {
"company": "string",
"address": {
"city": "Tallin",
"street": "New Street"
}
},
"recipient": {
"name": "Peter",
"phone": 30258554455
}
}';
$arr = json_decode($json_string, true);
var_dump($arr);
And if you want to revert is back to a json string, use json_encode()
$json_string = json_encode( $arr );
json_decode – https://www.php.net/manual/en/function.json-decode.php
json_encode – https://www.php.net/manual/en/function.json-encode.php
*note – the json string you provided in your original question was invalid (there’s a comma after cost).