如何使用 PHP 从 cURL 获取 json

Sil*_*gon 1 php json curl

我正在尝试使用 php 解码 cURL obtening 的 json,如下所示:

$url = 'https://www.toto.com/api/v1/ads/?apikey=titi&code_postal='.$code_postal.'&type_de_bois='.$type_bois;
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json'
));

$result = curl_exec($cURL);
curl_close($cURL);

var_dump(json_decode($result, true));
echo json_decode($result);
Run Code Online (Sandbox Code Playgroud)

这让我觉得,似乎是 json 的东西:

[{"id":"6918","nom":"X","code_postal":"88120","ville":"town","description":"test","logo":"test.png ","url":"test","telephone":true}, [{"id":"6919","nom":"Y","code_postal":"88121","ville":"town1" ,"description":"test","logo":"test.png","url":"test","telephone":true}, [{"id":"6920","nom":"Z ","code_postal":"88122","ville":"town2","description":"test","logo":"test.png","url":"test","telephone":true} ]

整数(1) 1

我的问题是: - 为什么在没有回显或打印的情况下打印数组?- 为什么 json_decode 不能正常工作或者为什么它只有一个值(“1”)?

非常感谢您的回答。

Bar*_*mar 7

您忘记使用该CURLOPT_RETURNTRANSFER选项。所以curl_exec()打印响应而不是将它返回到$result,并且$result只包含TRUE返回的值curl_exec以表明它是成功的。添加:

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
Run Code Online (Sandbox Code Playgroud)