server.php
// some code here .....
// this is the end of the file:
$json_data = array(
'test1'=>hello world,
'test2'=>hello stack
);
echo json_encode($json_data);
api.php
$text = api("http://example.com/?TEXT=$text&APIKEY=$apikey");
// return the json from server.php file
echo $text;
function api($url) {
$ch = curl_init();
$timeout = 20;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
文件api.php
成功返回json
{"test1":"hello world","test2":"hello stack"}
问题是当我尝试解析返回的JSON以获得test1
的值时,它没有显示任何内容。
我尝试了类似的东西,但无法解析JSON。
$obj=json_decode($text);
// dosent show anything
echo $obj->test1;
答案 0 :(得分:1)
在数组中的值周围加上引号。
$json_data = array(
'test1'=>"hello world",
'test2'=>"hello stack");