简单PHP微信文章采集并下载图片上传保存到七牛云

  • 时间:
  • 浏览:1626
  • 来源:无双科技

简单PHP微信文章采集并下载图片上传保存到七牛云

通过搜狗搜索采集公众号历史消息,在浏览器中打开要采集的文章链接地址。

具体的执行方法如下:

public function wxcaiji(){        if(request()->isAjax()){            $wxurl = input('wxurl');            if (config('sys.qiniu')) {                header("Content-type:text/html;charset=utf-8");                set_time_limit(1800);                require_once  ROOT_PATH.'app/extend/Qiniu/autoload.php';                // 需要填写你的 Access Key 和 Secret Key                $accessKey = config('sys.qiniu_accesskey');                $secretKey = config('sys.qiniu_secretkey');                $auth = new Auth($accessKey, $secretKey);                $bucket = config('sys.qiniu_bucket');                $domain = config('sys.qiniu_domain');                $bucketManager = new BucketManager($auth);                $html = curl($wxurl);                preg_match('/id="js_share_source".*?href="(.*?)"/i', $html, $match);                if (!empty($match[1])) {                    $match[1] = str_replace("http://", "https://", htmlspecialchars_decode($match[1]));                    $html = curl($match[1]);                }                preg_match('/(?<=id="activity-name">).*?(?=<\/h2>)/is', $html, $match);                if (empty($match[0])){                    return json(['code' => 0, 'msg' => "获取微信文章标题Error"]);                };                $title = $match[0];                preg_match('/(?<=id="js_content" style="visibility: hidden;">).*?(?=<\/div>)/is', $html, $match);                if (empty($match[0])){                    return json(['code' => 0, 'msg' => "获取微信文章内容Error"]);                };                $content = $match[0];//下载图片到七牛云//                $content = preg_replace_callback(//                    '/(?<=data-src="|url\(&quot;).*?(?="|&quot;\))/i',//                    function ($matches) use ($bucketManager, $bucket, $domain) {//                        list($ret, $err) = $bucketManager->fetch($matches[0], $bucket, null);//                        if ($err !== null) {//                            return $matches[0];//                        } else {//                            return $domain.$ret['key'];//                        }//                    },//                    $content//                );                $content = str_replace("data-src","src",$content);                return json(['code' => 1, 'title' => trim($title), 'content' => $content]);            }else{                return json(['code' => 0, 'msg' => "请先开启七牛云配置"]);            }        }    }


1、获取文章源代码:

通过php的函数file_get_content()就可以将文章源代码读取到变量中。

原文内容:

原文内容是包含在一个<p id='js_content'></p>标签中的,通过php代码获取:

正则的开头识别<p id='js_content'>,结尾识别<script/iUs,匹配到之后前面再补充一个<p id='js_content'>;我的正则匹配水平有限,只能写成这样的了。


2)内容处理:

通过上面的方法我们获得了文章内容的html,但是你将文章内容显示出来之后就会发现,图片和视频不能正常显示。因为这个html还需要一些加工:

首先是图片,微信文章中的<img>标签中的src属性全部都用了src属性代替。只有在显示的时候才会被替换过来。所以我们也有两个方案,将源代码直接替换过来,或者用js在显示时候再替换。

猜你喜欢