简体   繁体   English

json_decode出现问题

[英]Trouble with json_decode

For some reason I cannot seem to get json_decode to pull out the id I need. 由于某种原因,我似乎无法获取json_decode来提取所需的ID。 Perhaps I have a syntax error in this code? 也许我在这段代码中有语法错误? The code otherwise works. 该代码否则可以正常工作。 If I manually provide the id in between the two API calls it completes successfully. 如果我在两个API调用之间手动提供ID,则它将成功完成。 Also, I have not really been able to easily debug this because I am calling this PHP function using ajax and an html button and I dont really know Ajax at all, so I dont know how to print debug echo messages in the PHP code as I usually would to see where I am having trouble. 另外,我还不能真正轻松地调试它,因为我正在使用ajax和html按钮调用此PHP函数,而我一点也不了解Ajax,所以我不知道如何在PHP代码中打印调试回显消息。通常会看我哪里有麻烦。 So basically I am troubleshooting this blind. 所以基本上我是在对这个盲人进行故障排除。

Basically the code does an initial API call to find the VM with the tag "VMTAG". 基本上,代码会执行初始API调用以查找带有标签“ VMTAG”的VM。 The API call returns JSON info for that VM. API调用返回该VM的JSON信息。 I extract the ID with json_decode, then I do a second API call shutting down the VM using that ID. 我使用json_decode提取ID,然后执行第二次API调用,使用该ID关闭VM。

function shutdown() {
    $ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=VMTAG');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer TOKENHIDDEN',
        'Content-Type: application/json')
    );
    $json = curl_exec($ch);
    $object = json_decode($json);
    $id = $object['id'];
    $data = array("type" => "shutdown");
    $data_string = json_encode($data);
    $ch = curl_init('https://api.digitalocean.com/v2/droplets/' . $id . '/actions');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer TOKENHIDDEN',
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
    );
    $result = curl_exec($ch);
    exit;
} 

You have 你有

$object = json_decode($json); // this gives a stdClass
$id = $object['id'];          // you are using $object as an assoc. array

instead, 代替,

$object = json_decode($json,true); // now you have an assoc array and 
$id = $object['id'];               // $id should now be defined

see the docs for json_decode : 请参阅json_decode的文档:

http://php.net/manual/en/function.json-decode.php http://php.net/manual/zh/function.json-decode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM