3

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?

2
  • you can add them after convert the json to array after adding do the re-convert for get the json again. Commented Apr 25, 2016 at 4:45
  • Create an array that you needed for json then use json_encode Commented Apr 25, 2016 at 4:46

1 Answer 1

4

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":""}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.