我想知道如何从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数组而不是我想要显示的值。我需要隐藏所有其他值,然后只显示我想要的值。
答案 0 :(得分:2)
你需要告诉curl返回值,而不是打印它:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);