【发布时间】:2015-04-08 21:57:13
【问题描述】:
我是第一次使用 API。使用 cURL,我可以从 API 获取令牌并使用它来获取 JSON 格式文本的响应。这是我的代码:
<?php
$host = 'HOST';
$username = 'USERNAME';
$password = 'PASSWORD';
$payloadName = 'grant_type=client_credentials';
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($process, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
$str = ''.$return.'';
$start = strpos($str, '{');
$end = strpos($str, '}', $start - 1);
$length = $end - $start;
$json = substr($str, $start - 1, $length + 2);
$results = json_decode($json, true);
$token = $results['access_token'];
$type = $results['token_type'];
$curl = curl_init( "API URL?fields=title,author" );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $token) );
$return2 = curl_exec( $curl );
?>
我的问题是,为令牌解码 JSON 似乎工作正常,但 $return2 的值只是“1”或“true”,所以如果我使用相同的方法,就没有什么可解析的了。
这是输出文本结果,例如:
{"id":xxxxxx,"title":"War dogs","author":"Bear, Greg, 1951-"}
到网页,那么我如何将输出的内容捕获到我可以使用的变量中,无论是服务器端还是客户端?
【问题讨论】:
-
@dave - 那是红宝石,不是 PHP ;-)
-
@dbinns66 嗯,不,那是 JavaScript
-
@dave - LOL 在 ruby 中工作得很好 ;-) 我坐得更正了...