如何从简单的API响应中提取数据?

时间:2011-04-07 08:29:51

标签: php api

我收到了端点的api响应:

http://rest.sharethis.com/reach/getUrlInfo.php?url= 'http://www.mydomain.com/'

{ "email" : { "inbound" : 47498,
      "outbound" : "27459"
    },
  "facebook" : { "inbound" : 6311,
      "outbound" : "2301"
    },
  "other" : { "inbound" : 2196,
      "outbound" : "1456"
    },
  "sharethis" : { "inbound" : 16536,
      "outbound" : "7746"
    },
  "total" : { "inbound" : 80399,
      "outbound" : "40956"
    },
  "twitter" : { "inbound" : 4946,
      "outbound" : "1298"
    }
}

如何将“total”变量的“inbound + outbound”总和变为$ total等字符串,以便在php中回显。

2 个答案:

答案 0 :(得分:2)

$decoded = json_decode($string);
$inbound = $decoded->total->inbound;
$outbound = $decoded->total->outbound;
echo "Total: ".($inbound+$outbound);

答案 1 :(得分:1)

似乎是JSON。您应该查看json_decode(),它会将您的字符串转换为可以通过标准方式轻松操作的PHP数组。