非法字符串偏移'名称',代码使用示例json响应

时间:2017-02-18 22:33:50

标签: php json api

我目前正在建立一个网站,通过网页在家中控制我的SmartBulbs。为此,我使用提供的API。

我使用制造商网站上的示例json响应尝试了我的代码。一切正常,示例响应中列出的所有灯光都由div表示,并带有灯光名称。

当我在家里尝试我的代码(在代码中称为API)时,我得到了一个有效的响应,但我也收到了一个错误,其中声明非法字符串偏移'标签'。我做错了什么?

当我使用示例响应时,一切正常。我使用API​​时的响应对我来说看起来是一样的。它不应该也适用吗?

你可以在下面找到所有内容。如果你需要一些mor信息,请问:)

php代码

function get_lights(){

    $link = "https://api.lifx.com/v1/lights/all";
    $authToken = "I inserted my token here and got a valid response";

    $ch = curl_init($link);
    $headers = array('Authorization: Bearer ' . $authToken);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, $headers);
    $response = curl_exec($ch);

    $json = json_decode($response, true);

    $html = null;
    foreach($json as $object)
        {
        $html.= '<div class="element" onclick="get_info();">' . $object['label'] . '</div>';
        }

    return $html;

    }

示例回复

[
  {
    "id": "d3b2f2d97452",
    "uuid": "8fa5f072-af97-44ed-ae54-e70fd7bd9d20",
    "label": "Left Lamp",
    "connected": true,
    "power": "on",
    "color": {
      "hue": 250.0,
      "saturation": 0.5,
      "kelvin": 3500
    },
    "infrared": "1.0",
    "brightness": 0.5,
    "group": {
      "id": "1c8de82b81f445e7cfaafae49b259c71",
      "name": "Lounge"
    },
    "location": {
      "id": "1d6fe8ef0fde4c6d77b0012dc736662c",
      "name": "Home"
    },
    "last_seen": "2015-03-02T08:53:02.867+00:00",
    "seconds_since_seen": 0.002869418,
    "product": {
      "name": "LIFX+ A19",
      "company": "LIFX",
      "identifier": "lifx_plus_a19",
      "capabilities": {
        "has_color": true,
        "has_variable_color_temp": true,
        "has_ir": true,
        "has_multizone": false
      }
    }
  }
]

我的API响应

  [  
   {  
      "id":"d073d513bfd6",
      "uuid":"02ea5835-9dc2-4323-84f3-3b825419008d",
      "label":"MainLight",
      "connected":true,
      "power":"on",
      "color":{  
         "hue":27.581597619592586,
         "saturation":0.0,
         "kelvin":2500
      },
      "zones":null,
      "brightness":0.49999237048905165,
      "group":{  
         "id":"d5aa0e1180293e0af56607cbe47f4940",
         "name":"MyRoom"
      },
      "location":{  
         "id":"451e4b376a38062cdd10c54ab2698975",
         "name":"My Home"
      },
      "product":{  
         "name":"Color 1000",
         "identifier":"lifx_color_a19",
         "company":"LIFX",
         "capabilities":{  
            "has_color":true,
            "has_variable_color_temp":true,
            "has_ir":false,
            "has_multizone":false
         }
      },
      "infrared":null,
      "last_seen":"2017-02-18T21:40:58.164+00:00",
      "seconds_since_seen":0.001675218
   }
]

1 个答案:

答案 0 :(得分:0)

您为cURL句柄设置了错误的选项:

$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);