使用PHP解析API返回的JSON数据

时间:2013-10-14 00:55:44

标签: php json api parsing

我在这里使用API​​:http://developers.livechatinc.com/rest-api/#!chats

我正在尝试解析通过LiveChat服务提供商返回的数据。以下是API调用成功后返回的内容:

object(stdClass)#3 (3) {
  ["chats"]=>
  array(1) {
    [0]=>
    object(stdClass)#4 (17) {
      ["type"]=>
      string(4) "chat"
      ["id"]=>
      string(10) "MUQM3RLYBV"
      ["visitor_id"]=>
      string(22) "S1381706997.d8b6736611"
      ["agents"]=>
      array(1) {
        [0]=>
        object(stdClass)#5 (2) {
          ["display_name"]=>
          string(17) "Display Name"
          ["email"]=>
          string(30) "Email"
        }
      }
      ["supervisors"]=>
      array(0) {
      }
      ["rate"]=>
      string(10) "rated_good"
      ["duration"]=>
      int(50)
      ["group"]=>
      array(1) {
        [0]=>
        int(1)
      }
      ["started"]=>
      string(25) "Sun, 10/13/13 06:30:39 pm"
      ["pending"]=>
      bool(false)
      ["tags"]=>
      array(0) {
      }
      ["prechat_survey"]=>
      array(3) {
        [0]=>
        object(stdClass)#10 (3) {
          ["key"]=>
          string(5) "Name:"
          ["value"]=>
          string(12) "Demo Name"
          ["id"]=>
          string(18) "138133839826202879"
        }
        [1]=>
        object(stdClass)#11 (3) {
          ["key"]=>
          string(7) "E-mail:"
          ["value"]=>
          string(14) "demo@gmail.com"
          ["id"]=>
          string(18) "138133839826305342"
        }
        [2]=>
        object(stdClass)#12 (3) {
          ["key"]=>
          string(17) "Choose a Subject:"
          ["value"]=>
          string(4) "Math"
          ["id"]=>
          string(18) "138133839826304607"
        }
      }
      ["started_timestamp"]=>
      int(1381707039)
      ["ended_timestamp"]=>
      int(1381707089)
      ["ended"]=>
      string(25) "Sun, 10/13/13 06:31:29 pm"
    }
  }
  ["total"]=>
  int(1)
  ["pages"]=>
  int(1)
}

我很难抓住我需要从返回的数据中获取的某些数据。这是我一直在使用的代码,但它不起作用:

<?php
require_once('lib/LiveChat_API.php');

try {
    $LiveChatAPI = new LiveChat_API();
    $output = $LiveChatAPI->chats->get();
    $array = json_decode($output, true); //Saves the returned JSON object as a multi-dimensional array

    echo $array['prechat_survey']['E-mail'];

} catch (Exception $e) {
    die($e->getCode().' '.$e->getMessage());
}
?>

例如,我如何在“prechat_survey”下获得“电子邮件”的价值?

1 个答案:

答案 0 :(得分:1)

这会有用吗?

$array['prechat_survey'][1]['value'];

<强>更新

看起来你已经获得了一个对象,而不是一个JSON字符串......

试试看是否有效:

try {
    $LiveChatAPI = new LiveChat_API();
    $output = $LiveChatAPI->chats->get();

    echo $output->prechat_survey[1]->value;

} catch (Exception $e) {
    die($e->getCode().' '.$e->getMessage());
}

Upadte2我知道,有一个聊天对象我看不见

试试这个:

echo $output->chats[0]->prechat_survey[1]->value;
相关问题