php獲取頁面指定標籤內容的實現代碼分享

php獲取頁面指定標籤內容的實現代碼分享
能夠匹配任意可閉合帶id標籤 php

<?php
header ( "Content-type: text/html; charset=utf-8" );html

/*
* 參數說明: $tag_id:所要獲取的元素Tag Id $url:所要獲取頁面的Url $tag:所要獲取的標籤 $data
*/
function getWebTag($tag_id, $url = false, $tag = 'div', $data = false) {
    if ($url !== false) {
        $data = file_get_contents ( $url );
    }
    $charset_pos = stripos ( $data, 'charset' );
    if ($charset_pos) {
        if (stripos ( $data, 'utf-8', $charset_pos )) {
            $data = iconv ( 'utf-8', 'utf-8', $data );
        } else if (stripos ( $data, 'gb2312', $charset_pos )) {
            $data = iconv ( 'gb2312', 'utf-8', $data );
        } else if (stripos ( $data, 'gbk', $charset_pos )) {
            $data = iconv ( 'gbk', 'utf-8', $data );
        }
    }
    preg_match_all ( '/<' . $tag . '/i', $data, $pre_matches, PREG_OFFSET_CAPTURE ); // 獲取全部div前綴
    preg_match_all ( '/<\/' . $tag . '/i', $data, $suf_matches, PREG_OFFSET_CAPTURE ); // 獲取全部div後綴
    $hit = strpos ( $data, $tag_id );
    if ($hit == - 1)
        return false; // 未命中
    $divs = array (); // 合併全部div
    foreach ( $pre_matches [0] as $index => $pre_div ) {
        $divs [( int ) $pre_div [1]] = 'p';
        $divs [( int ) $suf_matches [0] [$index] [1]] = 's';
    }
    // 對div進行排序
    $sort = array_keys ( $divs );
    asort ( $sort );
    $count = count ( $pre_matches [0] );
    foreach ( $pre_matches [0] as $index => $pre_div ) {
        // <div $hit <div+1 時div被命中
        if (($pre_matches [0] [$index] [1] < $hit) && ($hit < $pre_matches [0] [$index + 1] [1])) {
            $deeper = 0;
            // 彈出被命中div前的div
            while ( array_shift ( $sort ) != $pre_matches [0] [$index] [1] && ($count --) )
                continue;
                // 對剩餘div進行匹配,若下一個爲前綴,則向下一層,$deeper加1,
                // 不然後退一層,$deeper減1,$deeper爲0則命中匹配,計算div長度
            foreach ( $sort as $key ) {
                if ($divs [$key] == 'p')
                    $deeper ++;
                else if ($deeper == 0) {
                    $length = $key - $pre_matches [0] [$index] [1];
                    break;
                } else {
                    $deeper --;
                }
            }
            $hitDivString = substr ( $data, $pre_matches [0] [$index] [1], $length ) . '</' . $tag . '>';
            break;
        }
    }
    return $hitDivString;
}ui

//test
echo getWebTag ( 'id="content"', 'http://www.cnblogs.com/suizhikuo/archive/2012/11/17/2774956.html', 'div' );
?>url

相關文章
相關標籤/搜索