myfile.php中有以下内容
$json_data = '{"type":"email","msg":"some text"}';
我想将php变量$ thetype和$ themsg连接到之前的行,而不是输入“email”或“some text”。
我该怎么做?无论我做什么,我都会遇到语法错误。
我正在尝试:
$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';
但正如我说错误一样。
非常感谢
答案 0 :(得分:8)
你的问题有点含糊......
你在找这个吗?
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
这会将$json_data
设置为类似您所描述的字符串:
<?php
$thetype = 'something';
$themsg = 'something else';
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
var_dump($json_data);
会打印:
string(43) "{"type":"something","msg":"something else"}"
请参阅the PHP manual for json_encode。
您可以尝试手动构建字符串,如下所示:
$json_data = '{"type":"'. addcslashes($thetype,"\"'\n").'","msg":"'. addcslashes($themsg,"\"'\n").'"}';
但是,你通常最好使用json_encode,因为它是为此目的设计的,并且不太可能产生无效的JSON。
答案 1 :(得分:-1)
PHP有一个编码json的函数。 但是,您需要将其输出为保存键的对象。 顺便说一下,这是一个3D阵列。
$data[]=array('type' => $thetype0, 'msg' => $themsg0);
$data[]=array('type' => $thetype1, 'msg' => $themsg1);
$json=json_encode((object)$data);
编辑:此方法应用于OLDER PHP版本。它与PHP 5.3兼容。 json_encode()函数对它进行了一些更改,因此PHP 5.2中的对象输出不可用。