'json'响应的类型在PHP中是boolean

时间:2018-05-07 13:22:57

标签: php json curl php-curl

我使用以下内容:

<?php
$url = '...';
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => "GET"
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$response = json_decode($response, true);
echo gettype($response); /$response/ THIS RETURNS INTEGER FOR SOME REASON!
?>

所以我得到的$response是整数类型,我无法读取这个JSON的元素。

另请注意,当我回应响应时,会在其后打印1。

2 个答案:

答案 0 :(得分:1)

查看手册以了解可能的return values。您至少需要使用CURLOPT_RETURNTRANSFER

  

成功时返回TRUE,失败时返回FALSE。但是,如果   设置CURLOPT_RETURNTRANSFER选项后,它将返回结果   成功,失败就错了。

<?php
$url = '...';
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_RETURNTRANSFER => true  // <<<< add this
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$response = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    var_dump(json_last_error_msg());
}

答案 1 :(得分:0)

&#39; $结果&#39;你的代码中没有定义,请仔细检查一下吗? 也许是&#34; $ response = json_decode($ response,true);&#34;需要改变。 未定义变量的默认值为NULL / False