Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Json to php Variables

Tags:

json

php

i want to make this json details dynamic.currently its static.as a example i want declare few php variables for these json.

Here is my code

$body = '{
  "outboundSMSMessageRequest": {
    "address": [
      "tel:+9456654978"
    ],

    "senderAddress": "tel:+95623654978",
    "outboundSMSTextMessage": {
      "message": "Welcome to fgf  Your Confirmation Code - "
    },

    "clientCorrelator": "",
    "receiptRequest": {
      "notifyURL": "",
      "callbackData": ""
    },
    "senderName": ""
  }
}';

As in here you can see json has declared to the $body.what i want to do is make separate variables such as $message,$address, $senderAddress and assign them to $body. how can i do this?

like image 593
colombo Avatar asked Feb 16 '26 22:02

colombo


1 Answers

Initial Json:

 $body = '{
      "outboundSMSMessageRequest": {
        "address": [
          "tel:+9456654978"
        ],

        "senderAddress": "tel:+95623654978",
        "outboundSMSTextMessage": {
          "message": "Welcome to fgf  Your Confirmation Code - "
        },

        "clientCorrelator": "",
        "receiptRequest": {
          "notifyURL": "",
          "callbackData": ""
        },
        "senderName": ""
      }
    }';

Decode json to array

I use the second parameter as true because i need the array as associative.

$arr = json_decode($body, true);

Now insert the necessary value:

$arr['outboundSMSMessageRequest']['address'] = "tel:+1234567890";
$arr['outboundSMSMessageRequest']['senderAddress'] = "tel:+0987654321";

$arr['outboundSMSMessageRequest']['outboundSMSTextMessage']['message'] = "test message";

Now Encode the array to json

$body = json_encode($arr);

Output

print_r($body);

Result

{"outboundSMSMessageRequest":{"address":"tel:+1234567890","senderAddress":"tel:+0987654321","outboundSMSTextMessage":{"message":"test message"},"clientCorrelator":"","receiptRequest":{"notifyURL":"","callbackData":""},"senderName":""}}
like image 143
Murad Hasan Avatar answered Feb 19 '26 11:02

Murad Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!