使用php&amp ;;记录curl GET请求的结果MySQL的

时间:2016-03-23 05:52:47

标签: php mysql curl

我正在尝试了解如何使用php记录curl GET请求的结果。我正在考虑将部分或全部结果输出到mysql。

https://github.com/cloudtrax/docs/blob/master/api/code/php/simple_api_server_test_harness.php

function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
    // get a curl handle then go to town on it
    $ch = curl_init($api_server . $endpoint);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);
    if ($result == FALSE) {
        if (curl_errno($ch) == 0)
            echo "@@@@ NOTE @@@@: nil HTTP return: This API call appears to be broken" . "\n";
        else
            throw new Exception(curl_error($ch), curl_errno($ch));    
    }
    else
      echo "RESULT: \n" . $result . "\n";
} 

$ result显示如下:

{
    "clients": {
        "ssid2": 4,
        "ssid1": 10
    },
    "rows": [
        {
            "time": "2016-03-23T02:45:00Z",
            "ssid2": {
                "traffic": {
                    "unclassified": {
//  etc...

如何将结果的每个部分与变量相关联,以便我可以输入太多的mysql?

3 个答案:

答案 0 :(得分:0)

看起来像json格式的结果。您可以使用json_decode对其进行解码:

$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result

答案 1 :(得分:0)

下面的代码会将json转换为PHP数组。然后,您可以使用数组的索引来提取值。

$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries

答案 2 :(得分:0)

如果您的回复是JSON响应,那么您只需使用php的json_decode来获取已解析的对象。

 $result = curl_exec($ch);
 //to get associative array passing true
 $jsonObj = json_decode($result, true);

 $clients = $jsonObj['clients'];
 $rows = $jsonObj['rows'];

您可以参考这些答案以获取更多详细信息: Parsing JSON object in PHP using json_decodeParsing JSON file with PHP