如何访问此json响应中的属性?

时间:2016-08-16 17:25:22

标签: php json rest response vtiger

我正在执行curl请求并获得一个返回json响应的响应。以下是回复回复后的代码。

回复:" Zeros取代了真正的令牌"

{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1

使用的代码(用于测试)和访问属性:     $ json = json_decode($ result);     的print_r($ JSON); //打印Json响应

$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
$secondtry = $json['token']; 

echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
print_r( $secondtry.'<br>');//Nothing Prints at all

我确实注意到一个奇怪的异常,它在最后打印出1,就好像我一样

json_encode($json);

返回响应用&#34; true&#34;替换字符串末尾的返回响应。 是&#34; 1还是真的&#34;最后是抛出json解码?

也许我错过了一些简单的东西?

如要求的完整测试代码

$url = "https://website.com/restapi.php";
//username of the user who is to logged in. 
$userName="adminuser"; //not real user

$fields_string; //global var


$fields = array( //array will have more in the future
'username' => urlencode($userName)
 );

//url-ify the data for the POST
foreach($fields as $key=>$value) { global $fields_string;
$fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,         $url.'?'.$fields_string.'operation=getchallenge');
curl_setopt($ch,CURLOPT_POST, count($fields));

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

3 个答案:

答案 0 :(得分:1)

json_decode(),默认情况下将子对象变为stdClass个对象而不是数组,除非它们是显式数组。

尝试类似:

$firsttry = $json->result->token;

答案 1 :(得分:0)

var_dump显示数据类型。由于str_pos本身是一个对象,因此请使用if [ ! -s ./testresults.txt ] ; then rm ./testresults.txt # or do something else else copy testresults.txt \\printserver\share fi 而非result

访问其令牌
->

答案 2 :(得分:0)

我想出了这个问题。在卷曲选项中我没有

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

一旦我把它放在@GentelmanMax解决方案中为我工作,但问题是在curl响应中直接响应,其中返回传输发回一个php可以使用的字符串,然后允许json_decode()作为应该。我知道这很简单。

相关问题