baike.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. $message = $this->message;
  3. $ret = preg_match('/(?:百科|定义)(.*)/i', $this->message['content'], $matchs);
  4. if (!$ret) {
  5. return $this->respText('请输入合适的格式, "百科+查询内容" 或 "定义+查询内容", 如: "百科姚明", "定义自行车"');
  6. }
  7. $word = $matchs[1];
  8. $url = 'https://wapbaike.baidu.com/searchresult?word=%s';
  9. $url = sprintf($url, $word);
  10. $resp = ihttp_get($url);
  11. if (200 == $resp['code'] && $resp['content']) {
  12. preg_match('|<ul.*id="searchList">.*</ul>|isU', $resp['content'], $content);
  13. if (!empty($content[0])) {
  14. $content = preg_replace('/(<em>|<em.*>|<\/em>)/', '', $content[0]);
  15. if (preg_match_all('|<li>.*<a href="(?<link>.+)">.*<span>(?<title>.+) - 百度百科</span>.*<p>(?<description>.+)</p>.*</a>.*</li>|isU', $content, $matchs)) {
  16. $ds = array();
  17. foreach ($matchs['title'] as $key => $v) {
  18. $ds[] = array(
  19. 'title' => strip_tags($v),
  20. 'link' => $matchs['link'][$key],
  21. 'description' => strip_tags($matchs['description'][$key]),
  22. );
  23. }
  24. $news = array();
  25. if (!preg_match('/^http(s)?:\\/\\/.+/',$ds[0]['link'])) {
  26. $ds[0]['link'] = 'https://baike.baidu.com' . $ds[0]['link'];
  27. }
  28. $news[] = array('title' => "{$word} 的百科解释如下", 'description' => $ds[0]['description'], 'picurl' => 'http://g.hiphotos.baidu.com/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=f38225303901213fdb3e468e358e5db4/9358d109b3de9c82afcae8666c81800a18d8bc3eb0356b97.jpg', 'url' => $ds[0]['link']);
  29. $cnt = min(count($ds), 8);
  30. for ($i = 0; $i < $cnt; ++$i) {
  31. $news[] = array(
  32. 'title' => $ds[$i]['title'],
  33. 'description' => $ds[$i]['description'],
  34. 'picurl' => '',
  35. 'url' => $ds[$i]['link'],
  36. );
  37. }
  38. return $this->respNews($news);
  39. }
  40. }
  41. }
  42. return $this->respText('没有找到结果, 要不换个词试试?');