【发布时间】:2015-04-03 10:20:39
【问题描述】:
这个问题让我很困惑。这是我的代码:
try {
//API Url
$url = 'https:<REST OF URL>';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'UserName' => '<HIDDEN>',
'Password' => '<HIDDEN>'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Execute the request
$content = curl_exec($ch);
catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
我使用浏览器运行 php 脚本,输出似乎是 json 格式,这正是我所需要的。但是,当我添加 json 解码并尝试 print_r 或 var_dump 输出时,我只是得到一个 boolean(true) 或 int(1),它不想将数据放入数组中。同样奇怪且最可能相关的是,上面的代码我没有使用 print_r、var_dump 甚至是 echo,但它仍然将 json 格式打印到屏幕上?
任何帮助将不胜感激。
编辑
这是显示在屏幕上的 json 输出:
{"AvailableAdvisers":[{"AdviserId":"1345678","BusinessEntityName":"Bob Smith Finance","FullName":"Bob Smith"},{"AdviserId":"12345678","BusinessEntityName":"Globe Home Loans Pty Ltd","FullName":"Jane Doe"}],"FirstName":"Sam","LastName":"Sung","LendingPartnerStaffId":"12345674356","Locations":[{"LendingPartnerLocationId":"123467867647","Name":"Bank"},{"LendingPartnerLocationId":"12324354545","Name":"Jane Smith"}],"UserName":"Username"}
【问题讨论】:
-
我看不出有什么话题可以讨论。所以你有你的
$content- 你var_dump($content);它是true值,但你想转换成什么?也许您应该向我们展示另一端的代码?生成对您的请求的响应,或者您使用什么服务?阅读文档,可能您需要更改一些请求参数? -
浏览器显示 API 返回了一个 json 字符串,因此人们会认为该 json 字符串是变量 $content。然而事实并非如此,当你 print_r($content) 它只显示整数 1。所以我需要 json 字符串为 $content,你明白我的意思吗?
-
不,绝对不。 1.您执行 curl 请求 2.请求成功执行并返回您放入
$content变量的内容。 3. 你确实打印了这个$content,你看到它只是int(1)。并且.....不知何故,我不知道您基于什么理由发表意见,但您确定此回复不完整。但事实证明它是完整的。 :-) 没什么可补充的 :-) -
好的。我编辑了帖子,当我运行上面的代码时,这是输出。不是json吗?在我的代码中,我在哪里设置了回显/打印这些数据?这是否表明返回的 json 字符串是 $content 的内容?但是当我 print_r($content) 时,它的值是 1。换句话说,哪个变量保存了上面的 json 字符串??