在php中向API发出请求

时间:2013-08-18 08:20:39

标签: php api

所以我想要一种方法来启动和关闭我的Droplet与Digital ocean,他们有自己的API,但我不太清楚如何做到

基本上我希望能够点击我网站上的按钮,服务器启动并显示JSON响应。 API网址是https://api.digitalocean.com/droplets/?client_id= [your_client_id]& api_key = [your_api_key]

,示例输出为:

{   “状态”:“好”,   “飞沫”:[     {       “id”:100823,       “名字”:“test222”,       “image_id”:420,       “size_id”:33,       “region_id”:1,       “backups_active”:false,       “ip_address”:“127.0.0.1”,       “锁定”:错误,       “状态”:“活跃”       “created_at”:“2013-01-01T09:30:00Z”     }   ] }

任何帮助都是apreciated

编辑:这是我试图开始工作的代码。

<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>Server Control Panel</title>
</head>
<body>
    <input type="submit" value="Start!" name="submit" id="Startbutton" />
    <input type="submit" value="Stop Server" name "submit2" id"Stopbutton" />
<?php
if (isset($_POST['submit'])) {
$request = 'https://api.digitalocean.com/droplets/377781/power_on/client_id=CLIENTIDGOESHERE&api_key=APIKEYGOESHERE';
$response  = file_get_contents($request);
$jsonobj  = json_decode($response);
echo($response);                
}
?>
<?php
if (isset($_POST['Stopbutton'])) {
$request = 'https://api.digitalocean.com/droplets/377781/shutdown/client_id=CLIENTIDGOESHERE&api_key=APIKEYGOESHERE';
$response  = file_get_contents($request);
$jsonobj  = json_decode($response);
echo($response);                
}
echo("</ul>"); 

?>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的表单缺少actionmethod个属性。您可能还希望将输入字段的名称属性重命名为更有意义的名称。

以下是具有一些改进的代码:

<?php

if (isset($_POST['Startbutton'])) 
{
    $request = 'https://api.digitalocean.com/droplets/377781/startup/client_id=CLIENTIDGOESHERE&api_key=APIKEYGOESHERE';
    $response  = file_get_contents($request);
    $jsonobj  = json_decode($response);
    echo "<pre>"; 
    print_r($jsonobj);       
    echo "</pre>";                 
}

if (isset($_POST['Stopbutton'])) 
{
    $request = 'https://api.digitalocean.com/droplets/377781/shutdown/client_id=CLIENTIDGOESHERE&api_key=APIKEYGOESHERE';
    $response  = file_get_contents($request);
    $jsonobj  = json_decode($response);
    echo "<pre>"; 
    print_r($jsonobj);       
    echo "</pre>";        
}

?>

<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>Server Control Panel</title>
</head>
<body>

<form action="" method="post">
    <input type="submit" value="Start!" name="Startbutton" id="Startbutton" />
    <input type="submit" value="Stop Server" name = "Stopbutton" id"Stopbutton" />
</form>

</body>
</html>

<强>更新

问题似乎与您的API网址有关。

/droplets/377781/startup/client_id=CLIENTIDGOESHERE&api_key=APIKEYGOESHERE

应该是:

/droplets/377781/startup/?client_id=CLIENTIDGOESHERE&api_key=APIKEYGOESHERE

请注意?之后丢失的/startup/

希望这有帮助!