PHP抓取公众号推文的高效方法
优采云 发布时间: 2023-04-25 05:36自媒体时代,推文是一种非常有效的传播方式。但是,手动抓取公众号的推文会耗费大量时间和精力。今天,我为大家介绍一种高效的方法——PHP抓取公众号推文函数。
1.准备工作
在使用PHP抓取公众号推文函数之前,我们需要先准备好以下工具:
- PHP环境
- Simple HTML DOM Parser插件
2.获取公众号文章列表链接
首先,我们需要获取公众号文章列表链接。可以通过以下方式获取:
-在微信中打开公众号主页,点击右上角的“阅读原文”按钮;
-在浏览器中打开文章页面,在地址栏中找到类似于“https://mp.weixin.qq.com/s/xxxxxxxxxxxxxx”的链接。
3.编写PHP代码
接下来,我们就可以开始编写PHP代码了。代码如下:
<?php
require_once('simple_html_dom.php');
function get_article($url){
$html = file_get_html($url);
$title =$html->find('#activity-name',0)->plaintext;
$content =$html->find('#js_content',0)->innertext;
return array('title'=>$title,'content'=>$content);
}
function get_articles($url){
$html = file_get_html($url);
$articles = array();
foreach ($html->find('.weui-media-box') as $media_box){
$link =$media_box->find('a',0);
$title =$link->find('.weui-media-box__title',0)->plaintext;
$url ='https://mp.weixin.qq.com'.$link->href;
$article = get_article($url);
$article['url']=$url;
$articles[]= array('title'=>$title,'article'=>$article);
}
return $articles;
}
?>
以上代码中,我们使用Simple HTML DOM Parser插件来解析HTML页面。get_article函数用于获取单篇文章的标题和内容,get_articles函数用于获取公众号文章列表。
4.使用PHP代码
最后,我们就可以使用PHP代码来抓取公众号推文了。代码如下:
<?php
require_once('get_articles.php');
$url ='https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIyMjE1MTkyNw==&scene=124#wechat_redirect';
$articles = get_articles($url);
foreach ($articles as $article){
echo '<h2>'.$article['title'].'</h2>';
echo '<p>'.$article['article']['content'].'</p>';
}
?>
以上代码中,我们先调用get_articles函数获取公众号文章列表,然后遍历文章列表,调用get_article函数获取单篇文章的标题和内容,并输出到页面上。
总结
今天,我们介绍了如何使用PHP抓取公众号推文函数。通过这种方法,我们可以轻松地获取公众号文章列表,并抓取单篇文章的标题和内容。这对于自媒体人士来说,是非常有用的工具。