colombo
colombo

Reputation: 520

Assign Json to php Variables

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?

Upvotes: 3

Views: 12152

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

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":""}}

Upvotes: 4

Related Questions