【问题标题】:Record the result of a curl GET request using php & mysql使用 php & mysql 记录 curl GET 请求的结果
【发布时间】:2016-03-23 05:52:46
【问题描述】:

我正在尝试了解如何使用 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?

【问题讨论】:

  • 没有一个答案可以完成这项工作,@shagun akarsh 这些链接让我更接近,但我的猜测是 json 的“深度”有些东西需要更好地订购。我的意思是“客户”是 1 级,然后“行”有自己的结构,然后“时间”在“ssid1”和“ssid2”下有 24 个结果
  • 进展感谢大家:` $jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($result, TRUE)), RecursiveIteratorIterator::SELF_FIRST);回声“
    ”; foreach ($jsonIterator as $key => $val) { if(is_array($val)) { echo "$key:\n";回声“
    ”; } else { echo "$key => $val\n";回声“
    ”; } }`

标签: php mysql curl


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果您的响应是 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-18
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多