在php中回显JSON数据
我试图回显一些JSON数据。问题是数据包含变量,但我的代码没有将变量放入字符串中。 这是我的密码:在php中回显JSON数据,php,json,Php,Json,我试图回显一些JSON数据。问题是数据包含变量,但我的代码没有将变量放入字符串中。 这是我的密码: $status = $row['Status']; $priority = $row['Priority']; echo '{"status":"$status","priority":"$priority"}' ; 这个php正在回响 {"status":"$status","priority":"$priority"} 当我需要回音的时候 {"status":"Completed","p
$status = $row['Status'];
$priority = $row['Priority'];
echo '{"status":"$status","priority":"$priority"}' ;
这个php正在回响
{"status":"$status","priority":"$priority"}
当我需要回音的时候
{"status":"Completed","priority":"High"}
比如说。如何修复此问题?问题在于您的单引号中,PHP将所有变量都作为字符串包含在内,因此请按如下方式断开字符串:
echo '{"status":"'.$status.'","priority":"'.$priority.'"}' ;
除此之外,您还可以使用json\u encode()
来避免手动构建json对象。只需使用函数即可
将为您提供所需的输出。这里的问题是PHP不会用单引号替换变量,而只用双引号替换变量(请参阅) 例如:
$test = "a";
echo 'This is $test test and'.chr(10);
echo "this is $test test.".chr(10);
/*
Creates the following output:
This is $test test and
this is a test.
*/
注意:chr(10)
创建新行
解决问题的方法是使用json\u encode()
和json\u decode()
,正如其他人已经建议的那样。
您不应该手动构建json,而是使用
json\u encode()
。
json_encode($row)
$test = "a";
echo 'This is $test test and'.chr(10);
echo "this is $test test.".chr(10);
/*
Creates the following output:
This is $test test and
this is a test.
*/