I have the following in myfile.php
$json_data = '{"type":"email","msg":"some text"}';
Instead of typing "email" or "some text" I want to concat the php variables $thetype and $themsg to the line before.
How can I do that? No matter what I do I get a syntax error.
I'm trying:
$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';
But as I say errors galore.
Thanks a lot
Your question is a little vague...
Are you looking for this?
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
That will set $json_data to a string like what you described:
<?php
$thetype = 'something';
$themsg = 'something else';
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
var_dump($json_data);
Would print:
string(43) "{"type":"something","msg":"something else"}"
See the PHP manual for json_encode.
You could try and build the string by hand, like this:
$json_data = '{"type":"'. addcslashes($thetype,"\"'\n").'","msg":"'. addcslashes($themsg,"\"'\n").'"}';
But, you'll generally be better off using json_encode, as it's designed for this purpose and is much less likely to produce invalid JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With