Comment interroger la liste des blagues en php

青灯夜游
Libérer: 2023-03-17 06:34:01
original
1538 Les gens l'ont consulté

Comment interroger le Joke Directory en PHP : 1. Ouvrez le service d'interface Joke Directory et obtenez la clé de demande d'identifiant d'appel de l'interface ; 2. Appelez l'API de l'interface pour faire une requête et obtenir les résultats de la requête (format json) ; 3. Utilisez json_decode() pour décoder le contenu de la requête. Analysez dans un tableau ; 4. Imprimez le contenu analysé, par exemple "var_dump (result array);".

Comment interroger la liste des blagues en php

L'environnement d'exploitation de ce tutoriel : système Windows 7, PHP version 8.1, ordinateur DELL G3

Exemple d'appel d'interface de collecte de blagues basée sur PHP

Préparation

  • Demander le interface

    Via https://www.juhe.cn/docs/api/id/95?s=cpphpcn Application libre-service pour ouvrir l'interface

  • Obtenez la clé de demande d'identifiant d'appel de l'interface

    Vous pouvez voir la clé de demande d'identifiant d'appel de cette interface dans Personal Center ➡️ Data Center ➡️ Mon module API

Veuillez lire attentivement l'interface du site officiel. Document, il s'agit de l'accord entre les données agrégées et les développeurs, il vous aidera à comprendre le métier de l'interface, afin d'effectuer le travail de développement en douceur

1. Obtenez la blague au hasard. interface

paramètres de demande

nom Obligatoire Type Description
clé est chaîne Afficher dans le Centre personnel- >Mes données, nom de l'interface

Exemple de code

//请求的接口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;
}
Copier après la connexion

Exemple de résultat de retour

array(3) {
  ["reason"]=>
  string(7) "success"
  ["result"]=>
  array(10) {
    [0]=>
    array(3) {
      ["content"]=>
      string(395) "【落马官员的基本特征】 嘴上学雷锋,心里学和珅; 赞扬焦裕禄,看齐雷政富; 都像孔繁森,全是王宝森; 八荣是讲话通稿,八耻是行为准则; 以党性作保证,以异性为猎物; 脱了裤子嫖妓,穿上裤子扫黄; 以国为家,国产变私产,爱民若子,民脂刮不止; 白天文明不精神,晚上精神不文明。"
      ["hashId"]=>
      string(32) "DE693E907034ADD4ABCF591B8181C13A"
      ["unixtime"]=>
      int(1425001334)
    }
    [1]=>
    array(3) {
      ["content"]=>
      string(235) "‍‍昨晚和老婆吵架了。 老婆:“气死我了,我要骂人了!” 然后,她对着我家汪汪一个劲的骂啊! 我:“我在这呢!你怎么骂汪汪啊?” 老婆回话了:“你!你还是人吗!”"
      ["hashId"]=>
      string(32) "88C00FC1B66D1EDA7912E54A2D6E0F89"
      ["unixtime"]=>
      int(1425001344)
    }
    [2]=>
    array(3) {
      ["content"]=>
      string(363) "  一次,我在公园玩悠悠球,一个小朋友跑过来问我:“哥哥,你玩的是什么呀?让我看看好吗?“我笑眯眯的答应,把悠悠球给了他,这时那小朋友的妈妈来了,小朋友举着我的悠悠球对他妈妈说:“妈妈,你看,这是哥哥送我的。”他妈妈说:“那还不快谢谢哥哥!”"
      ["hashId"]=>
      string(32) "9779B468CDE58940AABB7E826CB677D0"
      ["unixtime"]=>
      int(1425001379)
    }
    [3]=>
    array(3) {
      ["content"]=>
      string(243) "家里闹耗子了,问同事:你家里有猫不,借我养两天,吓吓老鼠。同事贱笑地对我说:不行,是母猫。艹,当哥没看过段子吗?回了句:哦,那你留着,自己用。留同事在风中凌乱……"
      ["hashId"]=>
      string(32) "98b9e3b27c3ac6c44d61ffa84e8a3a11"
      ["unixtime"]=>
      int(1425001431)
    }
    [4]=>
    array(3) {
      ["content"]=>
      string(837) "无论遇到什么事情;不要轻易说分手;不要轻易放弃感情;更别拿什么缘浅当借口;有时候感情差的就是一个转身而已;下一站未必会更好;感情再深;你不去呵护;慢慢就淡了;许多熟悉的事;你不去回味;渐渐就忘了;微笑;因一个人而起;痛苦;因一个人而生;一次冷落;会闷闷不乐;一句想你;会倍感幸福;所以;当爱在时;就要好好去珍惜;好缘分可遇不可求;有缘的人才能聚首;真感情可守不可丢;有爱的心永不说分手;别把真心爱过;变成曾经拥有;别把一次过错;变成一生错过;原谅并不难;只要感情深;永远并不远,只要彼此真。在一起不是说说而已,而是用心珍惜;真情意不是一时兴起;而是一世相依!"
      ["hashId"]=>
      string(32) "FC065A2FDFB0E7B1A661C08403C22153"
      ["unixtime"]=>
      int(1425001924)
    }
    [5]=>
    array(3) {
      ["content"]=>
      string(186) "妈妈给小明煮了两个鸡蛋,但是小明居然只吃了一个。妈妈心说孩子长大了知道心疼妈了。就问小明为啥留一个呢?小明说因为今天是剩蛋节"
      ["hashId"]=>
      string(32) "5DA85D97DA9E99F1C0C433768C50B890"
      ["unixtime"]=>
      int(1425001932)
    }
    [6]=>
    array(3) {
      ["content"]=>
      string(361) "说个我兄弟的,12年大年三十的晚上,这货没事干给10086客服拜年,结果口才好把人家小姑娘感动哭了,非要给他留电话,这是GC么?当然不是,GC是这小丫头被查到给用户留电话被开除了,更GC的是这两人还在一起了,现在开了个服装店,很苦也很幸福,今年就要结婚了……"
      ["hashId"]=>
      string(32) "1DDE835A3CCA61D149C0D0B8AA708885"
      ["unixtime"]=>
      int(1425001932)
    }
    [7]=>
    array(3) {
      ["content"]=>
      string(173) "‍‍‍‍“你爱我哪一点?”妇人问她的丈夫,“是我的天生丽质呢,还是我动人的身躯?” “我最爱你的这些幽默感。”‍‍‍‍"
      ["hashId"]=>
      string(32) "8F0BA8288787959CF6C818FC091128AB"
      ["unixtime"]=>
      int(1425001941)
    }
    [8]=>
    array(3) {
      ["content"]=>
      string(123) "问:“是不是复姓的人名字比较上档次?” 答:“欧阳翠花?”“宇文铁柱?”“司马来福?”"
      ["hashId"]=>
      string(32) "0CEC9589B4F2C445FC913A79910F9B36"
      ["unixtime"]=>
      int(1425002526)
    }
    [9]=>
    array(3) {
      ["content"]=>
      string(114) "朋友问我高原上蚊子多不,我回他说,不多,他问为啥,我说,你没听说那边缺痒呀?"
      ["hashId"]=>
      string(32) "91834BA3A265DD91527C1B7EB4188052"
      ["unixtime"]=>
      int(1425002536)
    }
  }
  ["error_code"]=>
  int(0)
}
Copier après la connexion

2 Requête de blagues par heure de mise à jour

Paramètres de demande

NomObligatoireTypeDescription
clé Oui stringdans Personal Center->Mes données, voir au-dessus du nom de l'interface
pageNonintNuméro de page actuel, par défaut 1, maximum 20
pagesizeNon intà chaque fois Nombre d'éléments retournés, par défaut 1, maximum 20
time est string horodatage (10 chiffres), tel que : 1418816972

exemple de code

<?php

//请求的接口URL
$apiUrl = &#39;http://v.juhe.cn/joke/content/list.php&#39;;

//请求参数
$params = [
    &#39;key&#39; => &#39;聚合数据上申请的接口调用key&#39;,
    &#39;sort&#39; => &#39;desc&#39;,
    &#39;time&#39; => &#39;1603439247&#39;,
    &#39;pagesize&#39; => 3
];
//参数数组转换成字符串
$paramsString = http_build_query($params);

//发起接口网络请求
$response = null;
try {
    $response = juheHttpRequest($apiUrl, $paramsString, 1);
} catch (Exception $e) {
    var_dump($e);
    //此处根据自己的需求进行具体的异常处理
}
if (!$response) {
    echo &#39;请求异常&#39; . PHP_EOL;
}
//接收接口返回内容
$result = json_decode($response, true);
if (!$result) {
    echo &#39;请求异常&#39; . PHP_EOL;
}
$errorCode = $result[&#39;error_code&#39;];
if ($errorCode == 0) {
    $data = $result[&#39;result&#39;];
} else {
    echo "请求异常:{$errorCode}_{$result[&#39;reason&#39;]}" . 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,  &#39;Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36&#39;);
    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 . &#39;?&#39; . $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;
}
Copier après la connexion

exemple de résultat de retour

array(3) {
  ["reason"]=>
  string(7) "Success"
  ["result"]=>
  array(1) {
    ["data"]=>
    array(3) {
      [0]=>
      array(4) {
        ["content"]=>
        string(294) "某先生是地方上的要人。一天,他像往常一样在书房里例览当日报纸,突然对妻子大声喊道:喂,安娜,你看到今天早报上的流言蜚语了吗?真可笑!他们说,你收拾行装出走了。你听见了吗?安娜、你在哪儿?安娜?啊!"
        ["hashId"]=>
        string(32) "90B182FC7F74865B40B1E5807CFEBF41"
        ["unixtime"]=>
        int(1418745227)
        ["updatetime"]=>
        string(19) "2014-12-16 23:53:47"
      }
      [1]=>
      array(4) {
        ["content"]=>
        string(192) "有一天我看着报纸,小声嘟囔着一篇文章的题目鸟儿也有外语,丈夫听了对了一句:鸟儿当然也有‘外遇’。原来丈夫听错了,我笑得前仰后合。"
        ["hashId"]=>
        string(32) "206F5C52FD2ED94772CBC66C8AC61F2A"
        ["unixtime"]=>
        int(1418745227)
        ["updatetime"]=>
        string(19) "2014-12-16 23:53:47"
      }
      [2]=>
      array(4) {
        ["content"]=>
        string(363) "新提拔的经理觉得从员工中得到的尊重不够,于是一天戴上一枚自制的徽章,上面写着:“我是头儿!”然后在办公室神气地来回巡视。中午吃完饭后,经理回到办公室,看见桌上留着一张字条,上面写着:“你的妻子打来电话,说让你记着下班后把徽章带回去,她要用。”"
        ["hashId"]=>
        string(32) "B36BF69DC3B622BD8A4F5A7740C31806"
        ["unixtime"]=>
        int(1418745227)
        ["updatetime"]=>
        string(19) "2014-12-16 23:53:47"
      }
    }
  }
  ["error_code"]=>
  int(0)
}
Copier après la connexion

3 .Dernières blagues

Paramètres de demande

NomObligatoireTypeDescription
clé isstring dans le centre personnel - >Mes données,interface Vue au dessus du nom
pagesizeNonintLe nombre d'éléments renvoyés à chaque fois, par défaut 1, maximum 20
pageNonint Numéro de page actuel, par défaut 1, maximum 20

Exemple de code

<?php

//请求的接口URL
$apiUrl = &#39;http://v.juhe.cn/joke/content/text.php&#39;;

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

//发起接口网络请求
$response = null;
try {
    $response = juheHttpRequest($apiUrl, $paramsString, 1);
} catch (Exception $e) {
    var_dump($e);
    //此处根据自己的需求进行具体的异常处理
}
if (!$response) {
    echo &#39;请求异常&#39; . PHP_EOL;
}
//接收接口返回内容
$result = json_decode($response, true);
if (!$result) {
    echo &#39;请求异常&#39; . PHP_EOL;
}
$errorCode = $result[&#39;error_code&#39;];
if ($errorCode == 0) {
    $data = $result[&#39;result&#39;];
} else {
    echo "请求异常:{$errorCode}_{$result[&#39;reason&#39;]}" . 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,  &#39;Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36&#39;);
    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 . &#39;?&#39; . $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;
}
Copier après la connexion

Exemple de résultat de retour

array(3) {
  ["reason"]=>
  string(7) "Success"
  ["result"]=>
  array(1) {
    ["data"]=>
    array(3) {
      [0]=>
      array(4) {
        ["content"]=>
        string(335) "    小区门口修车师傅生意特好。人实在,只要不换零件,常常不收钱或只收个块把钱辛苦钱。最近发现他心黑了,价钱明显上调,就连充个气也收1块钱。旁边书报亭大妈是知情人,: 唉,多担待一下吧!他家上个月二胎,一窝生了四个带把的。。。。"
        ["hashId"]=>
        string(32) "2e010657b420dcee335c870bf9a18301"
        ["unixtime"]=>
        int(1559789702)
        ["updatetime"]=>
        string(19) "2019-06-06 10:55:02"
      }
      [1]=>
      array(4) {
        ["content"]=>
        string(246) "前天和同事去逛超市,说好久没买肉吃了,于是去看猪肉,结果看到的最便宜的猪肉都要十八块多,同事当场惊呼:“猪怎么了,这是!”卖肉的师傅笑着说:“猪没事,就是涨价了。”"
        ["hashId"]=>
        string(32) "d261d1f0d76bdc665d80f104cf7a7d65"
        ["unixtime"]=>
        int(1556845202)
        ["updatetime"]=>
        string(19) "2019-05-03 09:00:02"
      }
      [2]=>
      array(4) {
        ["content"]=>
        string(518) "去小卖部买烟,10块钱一盒的,给老板100,老板喜咪咪的看着我说:“我没零钱找你,就让我闺女陪你一晚抵账得了。”我一激动:“你老别介啊,我攒个私房钱出来偷偷买烟,真的很不容易啊!”老板:“怎么,你不愿意?要不然我去把我闺女叫出来!”我:“别!别!这钱你不用找了,千万别让您闺女知道我藏私房钱啊!”老板:“好女婿,只要你经常来买东西,我保证不说!哈哈哈”"
        ["hashId"]=>
        string(32) "7d6e3f6cda682c18c3bc122a767b8756"
        ["unixtime"]=>
        int(1556845202)
        ["updatetime"]=>
        string(19) "2019-05-03 09:00:02"
      }
    }
  }
  ["error_code"]=>
  int(0)
}
Copier après la connexion

Apprentissage recommandé : "Tutoriel vidéo PHP"

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
php
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!