How i can use a variable ($_REQUEST('subject')) inside simple quotation marks.
This is my code:
<?php
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$postString = '{//i can't quit this quotation mark
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "$_REQUEST['subject'];",//this dont work
"from_email": "email#mydomain.com",
"from_name": "John",
"to": [
{
"email": "test#hotmail.com",
"name": "Bob"
}
],
"headers": {
},
"auto_text": true
},
"async": false
}';
?>
That's JSON! Use json_encode and json_decode!
$json = json_decode ($postString, true); // true for the second parameter forces associative arrays
$json['message']['subject'] = json_encode ($_REQUEST);
$postString = json_encode ($json);
Although, it looks like you could save a step and yourself some trouble if you just build $postString as a regular php array.
$postArr = array (
"key" => "myapi",
"message" => array (
"html" => "this is the emails html content",
"subject" => $_REQUEST['subject'],
"from_email" => "email#mydomain.com",
"from_name" => "John",
"to" => array (
array (
"email" => "test#hotmail.com",
"name" => "Bob"
)
),
"headers" => array (),
"auto_text" => true
),
"async" => false
);
$postString = json_encode ($postArr);
change "subject": "$_REQUEST['subject'];" to "subject": "' . $_REQUEST['subject'] . '"
Try this:
$postString = '{
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "'.$_REQUEST['subject'].'", // Modify this way
"from_email": "email#mydomain.com",
"from_name": "John",
....
.....
}';
Related
This is the array:
$response = array( 'message-count' => '1', 'messages' => array ( 0 => array ( 'to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111', ), ), );
What code do I use to get like, for example, the 'message-id' 's data?
I've tried $response->messages["message-id"];
but what I get is Trying to get property 'messages' of non-object
Tried a lot of others as well they are all returning the same error
I am quite new to this so I hope I could get some help here
Sorry:
Vardump gives me this, made a mistake with the code above
'{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}'
response is an array, you can't get messages like -> , You should get message-id by this way:
$jsonStr = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($jsonStr);
$messageId = $data->messages[0]->{'message-id'};
echo $messageId; //or var_dump($messageId)
Your array contains non-object values so you can retrieve the values as below.
<?php
$response = array('message-count' => '1', 'messages' => array(0 => array('to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111',),),);
echo $response['messages'][0]['message-id'];
// Output
// XXXXXXXXXXX
I would use array_column function like this
array_column($response['messages'], 'message-id');
$msg = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($msg);
$messageId = $data->messages[0]->{'message-id'};
var_dump($messageId);
If you have more than one message in the list then,
$messages = $data->messages;
foreach ($messages as $index => $message) {
var_dump($message); // whole message detail
var_dump($message->{'message-id'});// message-id
}
This question already has answers here:
Creating a jSON object using php loop
(2 answers)
Create a Json array in a for loop - php
(2 answers)
Closed 1 year ago.
How to add commas to a json print?
$result = curl($url);
$result = json_decode($result , true);
$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}
this is the response from my code
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
}
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
}
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
I want to have a comma for each json result
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:
$print = array();
foreach($resultdata as $data){
$print[]= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
}
print json_encode($print);
I don't get the point of having ',' but I'm guessing you want a valid json output. If so I guess that your result data is an array:
<?php
$result = [ 'data' => [
[
"id" => "17996292388215089",
"username" => "hanikfadhilah",
"text" => "Loh kapan ini huuu pengen"
],
[
"id" => "17877856039348099",
"username" => "titan_kdk",
"text" => "Mntb"
],
[
"id" => "17860767967398064",
"username" => "explorecentraljava",
"text" => "Terbaik fotonya lur"
]
]
];
so all what you need to do in order to get it as a valid json is:
print json_encode($result['data'], JSON_PRETTY_PRINT);
that produces output:
[
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
]
no need for any foreach loop.
json_encode()
I have a json that is mapped on an object. The json looks like above:
{
"employeeId": "1",
"firstName": "John",
"lastName": "Doe",
"departments": [
{
"fieldName": "department",
"fieldValue": "[dep1, dep2]"
}
]
}
I need to take data from "fieldValue" and put it into an array.
json_decode doesn't work for me since the values inside are not quoted. It would be very helpful if I had it like "fieldValue": "[\"dep1\",\"dep2\"]", but I cannot control how I receive it. Does somebody has some suggestions on how to make an array out of a string that looks like that?
Not sure that it is good variant, but you can use json_decode function two time:
$json = '{
"employeeId": "1",
"firstName": "John",
"lastName": "Doe",
"departments": [
{
"fieldName": "department",
"fieldValue": "[dep1, dep2]"
}
]
}';
$decodedJson = json_decode($json);
$fieldValue = json_decode(strtr($decodedJson->departments[0]->fieldValue, array(
'[' => '["',
']' => '"]',
',' => '","'
)));
var_dump($fieldValue);
$var = "[dev1, dev2]";
$keywords = preg_split('/[\[+\]]/', $var);
$keywords[1] will be your answer.
Then, you can split the $keywords[1] variable into an array using str_split()
I need to convert a JSON string in array using PHP, but I need to escape double quotes.
$string = '["label":"Name","type":"text","placeholder":"Mario","name":"name",*],
["label":"Email","type":"email","placeholder":"mail#example.com","name":"email",*],
["label":"Message","type":"textarea","value":"In this box you can insert a link"]';
$jsonify = strip_tags($string,"<a>");
$jsonify = str_replace('*','"required":"required"',$jsonify);
$jsonify = str_replace('[','{',str_replace(']','}',$jsonify));
$jsonify = str_replace(array("\r\n", "\r"),"",$jsonify);
$jsonify = preg_replace("/\s+/", " ", $jsonify);
$jsonify = '['.jsonify.']';
echo $jsonify;
// OUTPUT IS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail#example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a link"}]
// BUT IS NOT JSON VALID. IT SHOULD BE THIS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail#example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a link"}]
How can I obtain a valid JSON string?
your string is not a json valid
this is a $string json valid
[
{
"label": "Name",
"type": "text",
"placeholder": "Mario",
"name": "name"
},
{
"label": "Email",
"type": "email",
"placeholder": "mail#example.com",
"name": "email"
},
{
"label": "Message",
"type": "textarea",
"value": "In this box you can insert a <a href='#' target='_blank'>link</a>"
}
]
test this,and remove other code strip_tags,Str_replace,preg_replace
echo json_encode($string);
You get a valid json file by simply passing your array/string to json_encode like this :
$array = array(
array("label" => "Name", "type" => "text", "placeholder" => "Mario", "name" => "name"),
array("label" => "Email", "type" => "email", "placeholder" => "mail#example.com", "name" => "email"),
array("label" => "Message", "type" => "textarea", "value" => "In this box you can insert a <a href='#' target='_blank'>link</a>")
);
$json = json_encode($array);
var_dump($json);
So I'm trying to send a dynamic email with PHP. Now here's what I have
$postString = '{
"key": "xxx",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "email#email.com",
"from_name": "Joe",
"to": [
{
"email": "Joe# Joe",
"name": "Joe# Joe"
}
],
"attachments": [
]
},
"async": false
}';
Now I want "html" to be a variable. So I did this
"html": $var,
Sadly that doesn't work. Not does {} or using single quotes. Any ideas? It gets picked up as a string, by the way.
Variables are not interpolated in strings delimited by single quotes. There are a few ways around this. The following example uses concatenation.
$postString = '{
"key": "xxx",
"html": "' . $var . '",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "email#email.com",
"from_name": "Joe",
"to": [
{
"email": "Joe# Joe",
"name": "Joe# Joe"
}
],
"attachments": [
]
},
"async": false
}';
To be honest with you, this would be a lot easier if you just used an array and then encoded it into JSON using json_encode().
As mentioned in my comment, this would work a lot better
$post = [
'key' => 'xxx',
'message' => [
'html' => $var,
'text' => 'this is the emails text content',
'subject' => 'this is the subject',
'from_email' => 'email#email.com',
'to' => [
['email' => 'Joe# Joe', 'name' => 'Joe# Joe']
],
'attachments' => []
],
'async' => false
];
$postString = json_encode($post);
Obligatory legacy PHP note: If you're stuck on a PHP version lower than 5.4, you obviously can't use the shorthand array notation. Substitute [] with array() if that's the case.