TypechoJoeTheme

Lonhaiy的个人博客

登录
用户名
密码

Lonhaiy

如果结果不如你所愿,就在尘埃落定前奋力一搏
标签搜索
PHP

PHP JSON与cURL 函数

2022-08-26
/
0 评论
/
987 阅读
/
正在检测是否收录...
08/26

PHP JSON与cURL 函数

一、什么是 JSON ?

  • JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
  • JSON 是轻量级的文本数据交换格式
  • JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。 目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。
  • JSON 具有自我描述性,更易理解

二、JSON 函数

函数描述
json_encode对变量进行 JSON 编码
json_decode对 JSON 格式的字符串进行解码,转换为 PHP 变量
json_last_error返回最后发生的错误

1、json_encode

PHP json_encode() 用于对变量进行 JSON 编码,该函数如果执行成功返回 JSON 数据,否则返回 FALSE 。

实例

<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
echo json_encode($arr);//{"a":1,"b":2,"c":3,"d":4,"e":5}

$arr2 = ['name'=>'张三','name2'=>'李四','name3'=>'王五','name4'=>'赵六'];
echo json_encode($arr2,JSON_UNESCAPED_UNICODE);//{"name":"张三","name2":"李四","name3":"王五","name4":"赵六"}
?>
要注意的是 JSON_UNESCAPED_UNICODE 选项,如果我们不希望中文被编码,可以添加该选项。

2.json_decode

PHP json_decode() 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量。

实例

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));当第二个参数为 TRUE 时,将返回数组, FALSE 时返回对象,默认为 FALSE 。
?>

以上代码执行结果为:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

二、cURL 函数

CURL是PHP的一个扩展,利用该扩展可以实现服务器之间的数据或文件传输,用来采集网络中的html网页文件、其他服务器提供接口数据等。

实例(封装cURL函数)

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function curl_data($url, $params = false, $ispost = 0){
    $ch = curl_init();//创建了一个curl会话资源,成功返回一个句柄;
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // 默认值,让 cURL 自己判断使用哪个版本。 (强制使用 HTTP/1.1)。
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); // 在尝试连接时等待的秒数。设置为0,则无限等待。
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);  // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 要求结果保存到字符串中还是输出到屏幕上
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 爬取重定向页面
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);// 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算法是否存在
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // Post提交的数据包
        curl_setopt($ch, CURLOPT_URL, $url); // 设置URL
    } else {
        // GET请求,组装url
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch); // 运行cURL,请求URL,把结果复制给变量
    curl_close($ch);    // 关闭curl连接
    return $response;     // 返回获得的数据
}

三、实际应用

请求聚合天气查询接口,实现天气查询 http://www.lonhaiy.com/tqyb/index.php
<?php
//引入function.php 请求文件(把cUrl封装函数放在自己创建的function.php文件中)
require "function.php";
if(is_post()){
    if($_POST['city'] != ''){
        //接口请求地址
        $url = 'http://apis.juhe.cn/simpleWeather/query';
        //接口请求参数
        $parameter = [
            'city' => $_POST['city'],
            'key' => '' //你自己的key
        ];
        $res = json_decode(get_url($url,$parameter),true);
        if($res["error_code"] == 0) {
            $data = $res["result"];
        }
    }else{
        echo "<script>alert('请输入城市名称')</script>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>天气预报</title>
    <script src="./jquery.min.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
          crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
            crossorigin="anonymous"></script>
    <style>
        .main {
            max-width: 750px;
            margin: auto;
            padding: 15px;
        }
        .header{
            padding: 30px 0;
            margin: auto;
        }
        .header form{
            text-align: center;
        }
        .form-inline .form-group {
            display: inline-block;
            margin-bottom: 0;
            vertical-align: middle;
        }
        blockquote{
            border-left: 5px solid #1b809e;
        }
    </style>
</head>

<body>
<div class="main">
    <div class="header">
        <form class="form-inline" action="index.php" method="post">
            <div class="form-group">
                <input type="text" class="form-control" name="city" placeholder="请输入城市名称">
            </div>
            <button type="submit" class="btn btn-primary">天气查询</button>
        </form>
    </div>
    <?php if(isset($res)){ ?>
        <?php if($res["error_code"] == '0'){ ?>
            <div class="content">
                <blockquote>
                    <p>查询结果</p>
                </blockquote>
                <h5>今日天气</h5>
                <table class="table table-bordered table-hover">
                    <tr>
                        <td>城市</td>
                        <td><?=$data["city"]?></td>
                    </tr>
                    <tr>
                        <td>温度</td>
                        <td><?=$data["realtime"]["temperature"]?>℃</td>
                    </tr>
                    <tr>
                        <td>湿度</td>
                        <td><?=$data["realtime"]["humidity"]?>%</td>
                    </tr>
                    <tr>
                        <td>天气</td>
                        <td><?=$data["realtime"]["info"]?></td>
                    </tr>
                    <tr>
                        <td>风向</td>
                        <td><?=$data["realtime"]["direct"]?></td>
                    </tr>
                    <tr>
                        <td>风力</td>
                        <td><?=$data["realtime"]["power"]?></td>
                    </tr>
                    <tr>
                        <td>空气指数</td>
                        <td><?=$data["realtime"]["aqi"]?>%</td>
                    </tr>
                </table>
                <h5>未来几天天气</h5>
                <table class="table table-bordered table-hover">
                    <?php foreach($data["future"] as $k=>$v){ ?>
                        <tr>
                            <td><?=$v["date"]?></td>
                            <td>
                                <p><?=$v["temperature"]?></p>
                                <p><?=$v["weather"]?></p>
                                <p><?=$v["direct"]?></p>
                            </td>
                        </tr>
                    <?php } ?>
                </table>
            </div>
        <?php }elseif($res["error_code"] == '207301' || $res["error_code"] == '207302'){ ?>
            <div class="content">
                <blockquote>
                    <p>没有查到相关信息!</p>
                </blockquote>
            </div>
        <?php }elseif($res["error_code"] == '10012' || $res["error_code"] == '10013'){ ?>
            <div class="content">
                <blockquote>
                    <p>接口请求超过次数限制</p>
                </blockquote>
            </div>
        <?php } ?>
    <?php } ?>
</div>
</body>
</html>
赞(0)
版权属于:

Lonhaiy的个人博客

本文链接:

http://www.lonhaiy.com/index.php/archives/24/(转载时请注明本文出处及文章链接)

评论 (0)
Lonhaiy
如果结果不如你所愿,就在尘埃落定前奋力一搏
20 文章数
5,716 评论量

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月