Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat a php variable in a json line

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

like image 315
ADM Avatar asked Jul 15 '26 19:07

ADM


1 Answers

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.

like image 143
Josh Avatar answered Jul 17 '26 17:07

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!