您好我有一个脚本,它在数组中获取JSON输出,但我想只提取名称字段。它实际上是HostBill API,我只想打印域TLD。我尝试了所有的方法,但我收到了这个错误 注意:尝试在第22行的C:\ xampp \ htdocs \ hostbill \ check \ index.php中获取非对象的属性
我不知道代码有什么问题。
我要求的输出是: 产品名称:“。com”; 这是来自这个JSON “name”:“。com”,
我的PHP代码是:
<?php
$url = 'http://localhost/hostbill/admin/api.php';
$post = array(
'api_id' => '4c76ed9e1d48cc4f5d56',
'api_key' => '2056c9b03cc95ce625b1',
'call' => 'getProducts',
'id'=>1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
$return = json_decode($data, true);
print_r($return);
$product_name = $return->name;
echo "Product Name: ".$product_name;
?>
Hostbill JSON响应示例:
{
"success": true,
"products": {
"236": {
"id": "236",
"type": "9",
"name": "VPS-1024-w-sliders",
"stock": "0",
"paytype": "Free",
"description": "",
"m_setup": "0.00",
"q_setup": "0.00",
"s_setup": "0.00",
"a_setup": "0.00",
"b_setup": "0.00",
"t_setup": "0.00",
"d_setup": "0.00",
"w_setup": "0.00",
"h_setup": "0.00",
"m": "30.00",
"q": "0.00",
"a": "0.00",
"s": "0.00",
"b": "0.00",
"t": "0.00",
"d": "0.00",
"w": "0.00",
"h": "0.00",
"qty": "0",
"visible": "1",
"ptype": "onappcloud",
"accounts": "1"
},
"235": {
"id": "235",
"type": "9",
"name": "VPS-512-w-sliders",
"stock": "0",
"paytype": "Regular",
"description": "",
"m_setup": "0.00",
"q_setup": "0.00",
"s_setup": "0.00",
"a_setup": "0.00",
"b_setup": "0.00",
"t_setup": "0.00",
"d_setup": "0.00",
"w_setup": "0.00",
"h_setup": "0.00",
"m": "20.00",
"q": "0.00",
"a": "0.00",
"s": "0.00",
"b": "0.00",
"t": "0.00",
"d": "0.00",
"w": "0.00",
"h": "0.00",
"qty": "0",
"visible": "1",
"ptype": "onappcloud",
"accounts": "3"
}
},
"call": "getProducts",
"server_time": 1317712858
}
答案 0 :(得分:0)
产品位于array
,因此请使用foreach来迭代所有产品。
foreach($return['products'] AS $product){
echo "Product Name: ".$product['name'];
}
您还应该检查API响应是否有效。如果API不响应产品数组或响应空响应,则会出现错误。这样就可以了。
if(isset($return['products']) && is_array($return['products'])){
foreach($return['products'] AS $product){
echo "Product Name: ".$product['name'];
}
}
仅提取特定类别
要仅获取某些产品,请使用if
语句。例如,从category_id
1
和type
9
获取产品:
foreach($return['products'] AS $product){
if($product['category_id'] == 1 && $product['type'] == 9){
echo "Product Name: ".$product['name'];
}
}
答案 1 :(得分:0)
您将收到该错误,因为它不是对象。这是一个数组。
所以它应该是:
foreach($return['products'] as $key => $product){
echo "Product Name: ". $product['name'];
}