我从 API 获取的信息太多,我不能使用它,我只想从这个结果中得到"device_model"和"device_type",我该怎么做?我得到的结果是:
{"device_model":"模拟器","os_version":"7","浏览器":"Chrome","browser_version":"60","os":"Windows","device_type":"桌面","用户代理":"Mozilla/5.0 (视窗NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) 铬/61.0.3163.100 Safari/537.36","device_brand":"未知","is_bot":false}
移动检测接口
<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://useragentinfo.co/
$token = "#API_TOKEN";
$url = "https://useragentinfo.co/api/v1/device/";
$data = array('useragent' => $useragent);
$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
echo $json_response;
?>
如果你从 API 获得一个标准的 json 响应,你可以像这样json_decode()它并使用它:
<?php
// Do your curl request and get json_response here...
// Decode json response
$result = json_decode($json_response);
// All of the fields are then accessed like this:
// $result->device_model (for e.g.)
?>
<b>Device Model</b>: <?php echo $result->device_model ?>
<br>
<b>Device Type</b>: <?php echo $result->device_type ?>
etc...
如果您更喜欢使用数组,则可以执行以下操作:
// Decode json response
$result = json_decode($json_responsem true);
// Then use it like this:
// $result['device_model'] etc...