0

I'm trying to understand how to record the result of a curl GET request using php. I'm looking at outputing part or all of the result to 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";
} 

The $result shows like this:

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

How can I associate each part of the result too a variable so I can then input too mysql?

Michaël Azevedo
  • 3,874
  • 7
  • 31
  • 45
ballofjoy
  • 11
  • 5
  • none of the answers do the job, @shagun akarsh those links got me closer, but my guess is there is something about the 'depth' of the json which needs to be ordered better. I mean the "clients" is 1 level, then "rows" has its own structure then 'time' has 24 results under 'ssid1' and 'ssid2' – ballofjoy Mar 24 '16 at 00:30
  • progress thanks guys: ` $jsonIterator = new RecursiveIteratorIterator( new RecursiveArrayIterator(json_decode($result, TRUE)), RecursiveIteratorIterator::SELF_FIRST); echo "
    "; foreach ($jsonIterator as $key => $val) { if(is_array($val)) { echo "$key:\n"; echo "
    "; } else { echo "$key => $val\n"; echo "
    "; } }`
    – ballofjoy Mar 24 '16 at 02:01

3 Answers3

0

It looks like this result in json format. You can use json_decode to decode it:

$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
0

The code below will convert the json into a PHP array. You can then use the indexes of the array to pull out values.

$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries
Justice
  • 290
  • 2
  • 7
0

If your response is a JSON response then you can simply use php's json_decode to get parsed object.

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

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

You can refer to these answers for more detail: Parsing JSON object in PHP using json_decode and Parsing JSON file with PHP

Community
  • 1
  • 1
shagun akarsh
  • 159
  • 2
  • 14