php怎么查询笑话大全

php查询笑话大全的方法:1、开通笑话大全接口服务,获取接口的调用凭证请求key;2、调用接口API发出请求,获取查询结果(json格式);3、使用json_decode()将查询内容解析成数组;4、打印解析后的内容,例“var_dump(结果数组);”。

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本教程操作环境:windows7系统、PHP8.1版、DELL G3电脑

基于PHP的笑话大全接口调用示例

前期准备

  • 申请接口

    通过 https://www.juhe.cn/docs/api/id/95?s=cpphpcn 自助申请开通接口

  • 获取接口的调用凭证请求key

    可以在个人中心 ➡️ 数据中心 ➡️ 我的API 模块看到此接口的调用凭证请求key

请仔细阅读官网的接口文档,这是聚合数据与开发者的约定,它将有助于您对接口业务的理解,从而顺利地开展开发工作

1.随机获取笑话接口

请求参数

名称 必填 类型 说明
key string 在个人中心->我的数据,接口名称上方查看

代码示例

//请求的接口URL
$apiUrl = 'http://v.juhe.cn/joke/randJoke.php';

//请求参数
$params = [
    'key' => '聚合数据上申请的接口调用key',
];
//参数数组转换成字符串
$paramsString = http_build_query($params);

//发起接口网络请求
$response = null;
try {
    $response = juheHttpRequest($apiUrl, $paramsString, 1);
} catch (Exception $e) {
    var_dump($e);
    //此处根据自己的需求进行具体的异常处理
}
if (!$response) {
    echo '请求异常' . PHP_EOL;
}
//接收接口返回内容
$result = json_decode($response, true);
if (!$result) {
    echo '请求异常' . PHP_EOL;
}
$errorCode = $result['error_code'];
if ($errorCode == 0) {
    $data = $result['result'];
} else {
    echo "请求异常:{$errorCode}_{$result['reason']}" . PHP_EOL;
}
//打印接口返回结果
var_dump($result);

/**
 * 发起网络请求函数
 * @param String $url 请求的URL
 * @param bool $params  请求的参数内容
 * @param int $isPost   是否POST请求
 * @return bool|string  返回内容
 */
function juheHttpRequest($url, $params = false, $isPost = 0)
{
    $httpInfo = [];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT,  'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_TIMEOUT, 12);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($isPost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $reponse = curl_exec($ch);
    if ($reponse === FALSE) {
        // echo "cURL Error: ".curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $reponse;
}

登录后复制

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » php怎么查询笑话大全
温馨提示您:本站所载文章、数据仅供参考,如果有文章侵犯了您的权益,请来信告知我们删除,联系邮箱:976157886@qq.com
Copyright © 2023 自学咖网 - All rights reserved 浙ICP备2023005527号