【问题标题】:How can I echo a json value from a json array called from API [duplicate]如何从 API 调用的 json 数组中回显 json 值 [重复]
【发布时间】:2018-10-21 04:12:57
【问题描述】:

我想知道如何从 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 数组,而不是我想要显示的值。我需要隐藏所有其他值,只显示我想要的值。

【问题讨论】:

标签: php arrays json


【解决方案1】:

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

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2021-11-09
    • 2011-11-07
    • 2021-11-22
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多