如何使用PHP从cURL获取json [英] How to get json from cURL with PHP
问题描述
我正在尝试使用php将cURL解码的json解码为:
I'm trying to decode a json obtening by cURL with php like this :
$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);
那让我回想起,似乎是json:
That returns me that, something which seems to be json :
[{"id":"6918","nom":"X","code_postal":"88120","ville":"town","description":"test","logo":"test.png," url:" test,"电话:true}, [{{id:" 6919," nom:" Y," code_postal:" 88121," ville:" town1," description:" test," logo:" test.png ," url:" test,"电话:true}, [{{"id":"6920","nom":"Z","code_postal":"88122","ville":"town2","description":"test","logo":"test.png ," url:" test,"电话:true}]
[{"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}]
int(1)1
我的问题是: -为什么在没有回显或打印的情况下打印数组? -为什么json_decode无法正常工作,或者为什么它只是一个值("1")?
My question are : - Why, without echo or print, the array is printed? - Why json_decode doesn't work propely or why it is only one value ("1")?
非常感谢您的回答.
推荐答案
您忘记了使用CURLOPT_RETURNTRANSFER
选项.因此,curl_exec()
会打印响应,而不是将其返回到$result
中,并且$result
仅包含TRUE
所返回的值TRUE
,以指示该响应已成功.添加:
You forgot to use the CURLOPT_RETURNTRANSFER
option. So curl_exec()
printed the response instead of returning it into $result
, and $result
just contains the value TRUE
that was returned by curl_exec
to indicate that it was successful. Add:
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
这篇关于如何使用PHP从cURL获取json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!