首页 > 解决方案 > 如何从 API 调用的 json 数组中回显 json 值

问题描述

我想知道如何从我从 API 获得的 JSON 数组中获取任何值。

我正在调用这样的数据:

//initializing curl object
$curl = curl_init();
//adding fields to the curl object to enter the site
curl_setopt($curl, CURLOPT_URL, $my_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);  
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');

//executing the curl call and getting data back
$json = curl_exec($curl);

curl_close($curl); // close the connection  

我在我的 html 上打印了这个 json 数组:

[{"id":1,"name":"Books","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"200.0000"}],"tax":[]},{"id":2,"name":"pencil","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"5000.0000"}],"tax":[]}]

我想要的是从那个 json 数组中只得到一个或两个值,我的意思是我试过这个:

$code = json_decode($json, true);
echo $code[0]['id'];

但它似乎不起作用,因为我仍然在我的 HTML 中打印相同的 JSON 数组,而不是我想要显示的值。我需要隐藏所有其他值,只显示我想要的值。

标签: phparraysjson

解决方案


您需要告诉 curl 返回值,而不是打印它:

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  

推荐阅读