我在PHP中有一个函数,它接受JSON输出并返回它。我试图做的是返回StdClass对象,并在其周围添加一些字符串。所以要清楚,我需要将$ json包装在' JSON_CALLBACK()'中。由于无法在其周围附加字符串,我正在寻找另一种方法来实现我想要做的事情。
注意:' JSON_CALLBACK()'不是一个功能,它只是一个字符串。
这是我的代码:
public function showOutput() {
try {
$oauth = new OAuth($conskey,$conssec);
$oauth->fetch($api_base . '/uItems');
$json = json_decode($oauth->getLastResponse());
//return ($json);
}
catch(OAuthException $E) {
return($E);
}
echo "JSON_CALLBACK(";
return($json);
echo ")"; //wont do anything since return is already called so how can i append this with return?
}
答案 0 :(得分:0)
返回将是您函数的最后一行
echo "JSON_CALLBACK(";
return($json);// control will return back.
echo ")";// this will not work
return
之后的任何行都不会被执行。
所以,
return "JSON_CALLBACK($json)";
我不明白的一件事是你的流程根本不会出现在这条线上。
您已返回try
以及catch
答案 1 :(得分:0)
echo "JSON_CALLBACK(" . $json . ")";
return $json;
答案 2 :(得分:0)
以下是使用注释修复的代码,以帮助您了解更改。
public function showOutput() {
try {
$oauth = new OAuth($conskey,$conssec);
$oauth->fetch($api_base . '/uItems');
//don't decode since it is already json
//$json = json_decode($oauth->getLastResponse());
//don't return here, you will never reach the bottom of the code
//return ($json);
//get the json string instead
$json = $oauth->getLastResponse();
}
catch(OAuthException $E) {
//you can leave this return in here just in case there is a problem
//with oauth. This will stop the function if there was an error.
return($E);
}
//since this wasn't decoded, it is a string of json.
return "JSON_CALLBACK({$json})";
}
答案 3 :(得分:-1)
echo
打印到屏幕,而return
只返回一个值。
在文本中没有任何附带回报的意义。这没有意义。
如果您执行以下操作:
echo 'JSON_CALLBACK()';
return $json;
如果以某种方式执行最后一行,那么你的程序会给出的效果相同,因为return不会打印任何内容。
如果您只想打印,请在调用功能中打印。