PHP 获取参数 SN 并根据长度和串号信息请求 API 接口
以下是 PHP 代码示例,用于获取网页参数 SN,根据其长度和是否包含串号信息,分别请求不同的 API 接口,并输出获取到的 JSON 数据。
<?php
$sn = $_GET['sn'];
if (preg_match('/^\d{15}$/', $sn)) {
$url = 'https://example.com/2?i=' . $sn;
} else {
$url = 'https://example.com/1?i=' . $sn;
}
$response = file_get_contents($url);
$data = json_decode($response, true);
if (isset($data['result']['串号'])) {
$url = 'https://example.com/2?i=' . $data['result']['串号'];
$response = file_get_contents($url);
}
echo $response;
?>
代码解析:
-
获取参数
sn:使用$_GET['sn']获取网页地址栏中sn参数的值。 -
判断 SN 长度:使用正则表达式
/^\d{15}$/判断sn是否为 15 位数字。 -
构建请求 URL:根据 SN 长度,构建不同的 API 接口请求 URL:
- 如果 SN 为 15 位数字,则请求
https://example.com/2?i={sn}。 - 否则,请求
https://example.com/1?i={sn}。
- 如果 SN 为 15 位数字,则请求
-
发送请求:使用
file_get_contents()函数发送 GET 请求并获取 API 返回的 JSON 数据。 -
解析 JSON 数据:使用
json_decode()函数将 JSON 数据解析为数组。 -
判断是否存在串号:如果解析后的数组中存在
result['串号']键,则表示数据包含串号。 -
请求串号 API:如果存在串号,则再次构建请求 URL
https://example.com/2?i={串号},发送请求并获取 JSON 数据。 -
输出结果:最后,输出 API 返回的 JSON 数据。
代码示例中的 API 返回数据示例:
{'code': 0, 'result': '型号: iPhone 14 Pro Max 128GB 深空黑色<br>串号: 356041401122829<br>串号2: 356041401187590<br>序列号: KWT2DH77Q2<br>购买时间: 2023-02-2<br>销售国家: USA<br>网络锁: <span style='color:red;'>Chimaera Device Policy </span><br>运营商:<span style='color:red;'>Chimaera Device Policy </span><br>'}
说明:
- 代码中的
https://example.com/为示例 API 接口地址,请替换为实际地址。 - 代码假设 API 接口返回 JSON 格式的数据。
- 代码仅供参考,实际使用时可能需要根据具体情况进行调整。
相关知识点:
- PHP 中的
$_GET超全局变量 - PHP 中的正则表达式
preg_match()函数 - PHP 中的
file_get_contents()函数 - PHP 中的
json_decode()函数
原文地址: https://www.cveoy.top/t/topic/oflA 著作权归作者所有。请勿转载和采集!