Reputation: 333
I am trying to create a php script that outputs json in the following format but I don't seem to be getting around it.
{
"authentication_credentials": {
"api_key": "hybghhmimjij48fr847gt4fdf847v8",
"app_secret": "84984ff48448gf484198dfs818"
},
"sms_payload": [
{
"message": "Test Message",
"msisdn": "123456789",
"third_party_message_id": "samplestring"
}
],
"sender_id": "12345"
}
Here is the php code that I am trying to convert json
$api_key = "hybghhmimjij48fr847gt4fdf847v8";
$app_secret = "84984ff48448gf484198dfs818";
$message = "Test Message";
$msisdn = '123456789';
$third_party_message_id = 'samplestring';
$sender_id = '12345';
$data .= array('api_key'=>$api_key,'app_secret'=>$app_secret);
$data .= array('message'=>$message,'msisdn'=>$msisdn,'third_party_message_id'=>$third_party_message_id);
$data .= array('sender_id'=>$sender_id);
$data_string = json_encode($data);
echo $data_string;
What other twerks should I add to the code to make it output json in the above format.
Upvotes: 1
Views: 51
Reputation: 16117
You can encode as like that:
$data['authentication_credentials'] = array('api_key'=>$api_key,'app_secret'=>$app_secret);
$data['sms_payload'] = array('message'=>$message,'msisdn'=>$msisdn,'third_party_message_id'=>$third_party_message_id);
$data['sender_id'] = $sender_id;
echo json_encode($data);
Some Explanation:
As per your required json result you need to use associative array
not concatenated variables.
UPDATE 1:
After checking your last comments:
that is technically what i wanted to achieve. Thanks it solve my problem. – nick 7 hours ago
I am adding this solution as a UPDATE 1 for future visitors:
$data['sms_payload'] = array(
array(
'message'=>$message,
'msisdn'=>$msisdn,
'third_party_message_id'=>$third_party_message_id
));
Result:
"sms_payload":[{"message":"test","msisdn":"111","third_party_message_id":13213}]
Upvotes: 3
Reputation: 10143
Use option JSON_PRETTY_PRINT
$data_string = json_encode($data, JSON_PRETTY_PRINT);
echo $data_string;
More about this command
EDIT
And how I see, you have problems with data prepare, you must write something like this:
$data = (object)[
"authentication_credentials" =>
(object)[
'api_key' => $api_key,
'app_secret' => $app_secret
],
//...
];
Upvotes: 0