Blogger Information
Blog 19
fans 0
comment 0
visits 13232
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
通过curl请求接口实现数据读取
王浩
Original
610 people have browsed it
  1. 作业内容:1、把课上知识点练习。

  1. <?php
  2. /**
  3. * curl实现网络请求
  4. * @param $url 请求的网址
  5. * @param $data 数组或者字符串
  6. * @param $is_post 是否是POST请求
  7. * @return $output 返回的json数据
  8. */
  9. function Mycurl($url, $data=[], $is_post=0)
  10. {
  11. if($is_post){ // POST请求
  12. curl_setopt($ch, CURLOPT_POST, 1); // 表明是POST请求
  13. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  14. }else{ // GET请求
  15. if(is_array($data) && count($data) > 0){
  16. $url .= "?";
  17. foreach($data as $k=>$v){
  18. $url .= $k ."=".$v."&";
  19. }
  20. }
  21. }
  22. $ch = curl_init(); // 初始化,获取CURL句柄
  23. // 开始配置参数
  24. curl_setopt($ch, CURLOPT_URL, $url); //请求URL
  25. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  26. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  27. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据流,而不是直接输出
  28. curl_setopt($ch, CURLOPT_HEADER, 0); //无需响应的header头
  29. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //设置响应超时时间,单位为秒
  30. //去除最后一个拼装的&符号
  31. $url = rtrim($url, '&');
  32. // 执行并获取返回数据
  33. $output = curl_exec($ch);
  34. if($output === false){
  35. $output = "curl error: ". curl_errno($ch);
  36. }
  37. curl_close($ch);
  38. return $output;
  39. }
  40. // 通过聚合接口获取笑话列表
  41. $url = 'http://v.juhe.cn/joke/content/text.php';
  42. $data = [
  43. "page" => 1, // 当前页数,默认1,最大20
  44. "pagesize" => 5, // 每次返回条数,默认1,最大20
  45. "key" => '6ddde091291b4c2b37b385b7d84c1ffd' //key
  46. ];
  47. $joke_json = Mycurl($url, $data);
  48. $joke_obj = json_decode($joke_json, true);
  49. echo '<table><tr><th>笑话列表</th></tr>';
  50. foreach($joke_obj['result']['data'] as $k=>$v){
  51. echo '<tr>';
  52. echo '<td>'.$v['content'].'</td>';
  53. echo '</tr>';
  54. }
  55. echo '</table>';
  56. ?>
  57. <style>
  58. table{
  59. width: 400px;
  60. border-collapse: collapse;
  61. }
  62. th{
  63. padding: 20px;
  64. }
  65. td{
  66. padding: 15px;
  67. border: 1px solid #ccc;
  68. }
  69. </style>
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post