码迷,mamicode.com
首页 > Web开发 > 详细

PHP通过DOMDocument对象来抓取网页中的指定class的内容

时间:2020-11-20 12:00:20      阅读:20      评论:0      收藏:0      [点我收藏+]

标签:document   指定   array   com   tco   his   通过   fun   color   

 

<?php

function getTagClassContent($url, $tagName, $className) //要抓取的网页, 要抓取的Tag名, 要抓取的Class名
{
    $doc = new DOMDocument();
    @$doc->loadHTML(file_get_contents($url)); 
    $nodes = $doc->getElementsByTagName($tagName); 
    
    $res = array();
    foreach($nodes as $n) {
        if($attrItemClass = $n->attributes->getNamedItem(‘class‘)) {
            if($classes = explode(‘ ‘, $attrItemClass->textContent)) {
                if(in_array($className, $classes)) {
                    
                    $res[] = $n->textContent;
                }
            }
        }
    }
    
    return $res;
}

$res = getTagClassContent(‘http://www.dyhjw.com/meiyuanzhishu‘, ‘span‘, ‘nom‘);

var_dump($res);

/*
输出:
array(1) {
  [0]=>
  string(7) "92.7375"
}
*/

 

PHP通过DOMDocument对象来抓取网页中的指定class的内容

标签:document   指定   array   com   tco   his   通过   fun   color   

原文地址:https://www.cnblogs.com/bird-eat-vegetable/p/13983166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!