牛骨文教育服务平台(让学习变的简单)
博文笔记

PHP-文章简单采集

创建时间:2017-02-16 投稿人: 浏览次数:1552

以下是在wamp环境下PHP利用文件操作,获取url,达到文章采集效果

<?php
    //文章采集方法一
/*  $res = fopen("http://www.huanqiu.com/","r");
    $data ="";
    while($strcon = fgets($res)){
        $data .= $strcon;
    }
    fclose($res);*/

    //文章采集方法二
    $data = file_get_contents("http://www.huanqiu.com/");
    $data1 = file_get_contents("http://china.huanqiu.com/article/2017-02/10136020.html");
    $data2 = file_get_contents("http://opinion.huanqiu.com/editorial/2017-02/10135124.html");
    $data3 = file_get_contents("http://world.huanqiu.com/exclusive/2017-02/10137395.html");
    //标题正则
    $div_preg = "/<div id="block_id_42876" class="admin_block" blockid="42876">[sS]+?</div>/";
    $title_preg = "/<h4>[sS]+?</h4>/";
    //内容正则
    $con_preg = "/<div class="conText">[sS]+?<!-- 左侧 end -->/";
    //得到返回的数组数据
    preg_match($div_preg,$data,$arr);
    preg_match($con_preg,$data1,$arr1);
    preg_match($con_preg,$data2,$arr2);
    preg_match($con_preg,$data3,$arr3);
    //匹配数据里所有需要的标签内容
    preg_match_all($title_preg,$arr[0],$arrT);
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章采集</title>
    <style type="text/css">
    ul,li{
        margin: 0;
        padding: 0;
        list-style:none;
    }
    .con{
        width: 420px;
        height: 460px;
        float: left;
        margin-right: 20px;
        overflow: auto;
        border: 2px solid #ccc;
        border-radius: 10px;
        box-shadow: 4px 5px 3px #aaa;
    }
    </style>
</head>
<body>
    <ul>
    <?php foreach ($arrT[0] as $key => $value):?>
        <li><?php echo $value;?></li>
    <?php endforeach;?>
    </ul>
    <ul>
        <div class="con"><?php echo $arr1[0];?></div>
        <div class="con"><?php echo $arr2[0];?></div>
        <div class="con"><?php echo $arr3[0];?></div>
    </ul>
</body>
</html>
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。