我从这样的API调用数据:
$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);
//executing the curl call and getting data back
$jsonStr = curl_exec($curl);
curl_close($curl); // close the connection
print_r($jsonStr);
它工作正常,但问题是我无法解码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":[]}]
我试图解码并调用像“echo $ code [0] ['name']这样的值;”我不能,它显示相同的json数组,然后我试图将json数组保存为变量,如:
$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":[]}]';
并试图解码它,它的工作原理,我认为问题是单引号 . 我不确定,但这是我假设基于我得到的结果 . 我是curl,json和php的新手,所以如果有人可以帮助我 .
顺便说一句,我试图像这样解码:
$code = json_decode($jsonStr ,true);
echo $code[0]['id'];
但它不起作用,它返回相同的完整json数组,而不是我想要的值
当我试图回应$ jsonStr我得到:
[{"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":[]}]
3 回答
您可以使用json_decode()方法
请参考此链接http://php.net/manual/en/function.json-decode.php
使用
json_decode()
. 如果您想查看php对象以便更好地了解如何使用它,请尝试不知道为什么不适合你 . 当json字符串在代码中时它确实有效 .
输出继电器:
顺便说一下我的版本