新手日记,求大佬们别喷
<?php
namespace App\Http\Controllers\WeChat\JianJian;
use App\Models\article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\user;
//数据库
//user=['id','openid','list']其他自行添加
//article=['id','userid','title','body']其他自行添加
class WebGetController extends Controller
{
function save_to_list($id,$article_id){
$user=user::find($id);
$user_list=$user->list;
if($user_list){
$user->list=$article_id;
}else{
$user->list=$user_list.",".$article_id;
}
$user->save();
return "文章保存成功,感谢你的使用";
}
function get_id($openid){
return user::where('openid','=',$openid)->first()->id;
}
function save_article($openid,$url){
$id=$this->get_id($openid);
if($id==""){return "很抱歉,请先从菜单进入简简看文页面创建用户.";}
$article_info=$this->get_title_body($url);
$article=new article;
$article->title=$article_info['title'];
$article->body=$article_info['body'];
$article->userid=$id;
$article->save();
$article_id=$article->id;
return $this->save_to_list($id,$article_id);
}
function get_title_body($url){
$html= file_get_contents($url);
$data=$this->compress_html($html);
unset($html);
$pattern= "/<h2 class=\"rich_media_title\"id=\"activity-name\">([\s\S]*?)<\/h2>/i";
preg_match_all($pattern, $data, $matches);
$title=$matches[1][0];
$pattern= "/<div class=\"rich_media_content\"id=\"js_content\">([\s\S]*?)<\/div>/i";
preg_match_all($pattern, $data, $matches);
$body=$matches[1][0];
unset($data);
return ['title'=>$title,'body'=>$body];
//return $result = file_get_contents($url);
}
//下面是压缩html,去掉不必要的符号
function compress_html($string) {
$string = str_replace("\r\n", '', $string); //清除换行符
$string = str_replace("\n", '', $string); //清除换行符
$string = str_replace("\t", '', $string); //清除制表符
$pattern = array (
"/> *([^ ]*) *</", //去掉注释标记
"/[\s]+/",
"/<!--[^!]*-->/",
"/\" /",
"/ \"/",
"'/\*[^*]*\*/'"
);
$replace = array (
">\\1<",
" ",
"",
"\"",
"\"",
""
);
return preg_replace($pattern, $replace, $string);
}
}