本文利用php實現跨域解析獲取HTML標簽,返回值中將包含1個或多個匹配的標簽結果。
從圖中可看出,輸入參數包括:URL鏈接,HTML源碼,標簽名,標簽屬性,是否僅匹配第一項。
1、URL鏈接
用於非輸入HTML源碼情況下獲取HTML源碼。這個較為通用。
2、HTML源碼
任意用於測試用的HTML源碼都可以。
3、標簽名
標簽名可為任意HTML標簽,包括div,ul,table等。
4、標簽屬性
標簽屬性可用於精確匹配標簽,可為:id="main",class="p",name="task",border="0px"等。
5、是否僅匹配第一項
只獲取第一條返回結果。
一些效果圖如下:
(圖一 URL鏈接方式)
(圖二 直接輸入HTML源碼方式)
(圖三 匹配class屬性)
(圖四 匹配所有<a>標簽)
(圖五 只獲取第一個匹配項)
源碼展示:

1 <html> 2 <head> 3 <title>parse DIV</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <meta http-equiv="Content-Language" content="zh-CN" /> 6 <script type="text/javascript" src="http://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script> 7 </head> 8 <body> 9 <span><div>請輸入URL鏈接:</div><input type="text" id="url" value="http://www.baidu.com/">(如:http://www.baidu.com/)</span> 10 <span><div>此次可直接輸入頁面HTML:</div><input type="text" id="data" value="">(若輸入請清空上面URL鏈接)</span> 11 <span><div>請輸入HTML標簽名:</div><input type="text" id="tag" value="div">(如div,ul,table,tr,img,input,h1等)</span> 12 <span><div>請輸入HTML標簽的屬性:</div><input type="text" id="tag_id" value='id="u"'>(如id="main",id='main',class="p",name="task"等,可留空匹配無屬性標簽,區分單雙引號)</span> 13 <span><div>只獲取第一個匹配項:</div><input type="radio" id="first" now-v="unchecked"></span> 14 <span><input type="button" value="提交" id="parse"></span> 15 <span>解析結果:</span> 16 <textarea id="result" style="float:left;" cols="150" rows="20"></textarea> 17 <script type="text/javascript"> 18 $(document).ready(function(){ 19 //初始化 20 $("body").css({"background-color":"#ABC"}); 21 $("span").css({"float":"left","clear":"both","padding":"3px"}); 22 $("div").css({"float":"left","width":"300px"}); 23 $("input").attr('size',40); 24 $("#first").attr('checked',null); 25 //單選按鈕操作 26 $("#first").unbind().click(function(){ 27 if($(this).attr('now-v') == 'unchecked') $(this).attr('checked','checked').attr('now-v','checked'); 28 else $(this).attr('checked',null).attr('now-v','unchecked'); 29 }) 30 //提交處理 31 $("#parse").click(function(){ 32 var tag_id,url,tag,data,parentBegin='',parentEnd=''; 33 var first = encodeURIComponent($("#first").attr('now-v')); 34 $("input[type=text]").each(function(){ 35 var name = $(this).attr('id'); 36 var value = $.trim($(this).val()); 37 if(value == '') value='EmPtYValue'; 38 value = encodeURIComponent(value); 39 eval(name+'="'+value+'"'); 40 if(eval(name) == '') return false; 41 }); 42 switch(tag){ 43 case 'td': 44 parentBegin = '<table><tr>'; 45 parentEnd = '</tr></table>'; 46 break; 47 case 'tr': 48 parentBegin = '<table>'; 49 parentEnd = '</table>'; 50 break; 51 case 'li': 52 parentBegin = '<ul>'; 53 parentEnd = '</ul>'; 54 break; 55 case 'dt': 56 parentBegin = '<dl>'; 57 parentEnd = '</dl>'; 58 break; 59 default: 60 parentBegin = ''; 61 parentEnd = ''; 62 break; 63 } 64 65 $.ajax({ 66 url:'parseHtml.php', 67 type:'POST', 68 dataType:'json', 69 async:false, 70 data:{"tag_id":tag_id,"url":url,"tag":tag,"data":data,"first":first}, 71 success:function(msg){ 72 if(msg != '沒有匹配項!') var count = "一共獲得"+msg.length+"個匹配。\n"; 73 else var count = ''; 74 $("#result").html(count+parentBegin+msg.toString().replace(/>,</g,">\n<")+parentEnd); 75 // alert(msg[0]); //獲取第1個匹配 76 // alert($(msg[1]).html()); //獲取第2個匹配html內容 77 }, 78 error:function(){ 79 alert("服務器出錯"); 80 } 81 }); 82 }); 83 }); 84 </script> 85 </body> 86 </html>

1 <?php 2 header("Content-type: text/html; charset=utf-8"); 3 function getWebTag($tag_id,$url=false,$tag='div',$data=false,$first=false){ 4 //默認采用URL獲取數據 5 if($url !== false){ 6 $data = file_get_contents( $url ); 7 } 8 //頁面編碼判定及轉碼 9 $charset_pos = stripos($data,'charset'); 10 if($charset_pos) { 11 if(stripos($data,'charset=utf-8',$charset_pos)) { 12 $data = iconv('utf-8','utf-8',$data); 13 }else if(stripos($data,'charset=gb2312',$charset_pos)) { 14 $data = iconv('gb2312','utf-8',$data); 15 }else if(stripos($data,'charset=gbk',$charset_pos)) { 16 $data = iconv('gbk','utf-8',$data); 17 } 18 } 19 20 //匹配命中標簽至數組$hits 21 preg_match_all('/<'.$tag.'[^<]*?'.$tag_id.'/i',$data,$hits,PREG_OFFSET_CAPTURE); 22 if(count($hits[0]) === 0) { //未命中,直接返回 23 return '沒有匹配項!'; 24 } 25 26 preg_match_all('/<'.$tag.'/i',$data,$pre_matches,PREG_OFFSET_CAPTURE); //獲取所有HTML標簽前綴 27 preg_match_all('/<\/'.$tag.'/i',$data,$suf_matches,PREG_OFFSET_CAPTURE); //獲取所有HTML標簽后綴 28 29 //判斷是否<div></div>格式,是則添加結束標簽,否則為false; 注:img、input等可能不是這種格式,此時$suf_matches[0]為空。 30 if(!empty($suf_matches[0])) $endTag = '</'.$tag.'>'; 31 else $endTag = false; 32 33 //合並所有HTML標簽 34 $htmltags = array(); 35 if($endTag !== false){ 36 foreach($pre_matches[0] as $index=>$pre_div){ 37 $htmltags[(int)$pre_matches[0][$index][1]] = 'p'; 38 $htmltags[(int)$suf_matches[0][$index][1]] = 's'; 39 } 40 }else{ 41 foreach($pre_matches[0] as $index=>$pre_div){ 42 //非<div></div>格式,獲取前綴下標后的第一個>作為標簽結束 43 $suf_matches[0][$index][1] = stripos($data,'>',$pre_matches[0][$index][1])+1; 44 45 $htmltags[(int)$pre_matches[0][$index][1]] = 'p'; 46 $htmltags[(int)$suf_matches[0][$index][1]] = 's'; 47 } 48 } 49 //對所有HTML標簽按index進行排序 50 $sort = array_keys($htmltags); 51 asort($sort); 52 53 //開始獲取命中字符串 54 $hitTagStrings = array(); 55 foreach($hits[0] as $hit){ 56 $hit = $hit[1]; //獲取命中index 57 58 $count = count($sort); //循環控制,$count--避免無限循環 59 foreach($pre_matches[0] as $index=>$pre_div){ 60 //最后一個$pre_matches[0][$index+1]會造成數組出界,因此設置其index等於總長度 61 if(!isset($pre_matches[0][$index+1][1])) $pre_matches[0][$index+1][1] = strlen($data); 62 63 //<div $hit <div+1 時div被命中 64 if(($pre_matches[0][$index][1] <= $hit) && ($hit < $pre_matches[0][$index+1][1])){ 65 $deeper = 0; 66 //彈出被命中HTML標簽前的所有HTML標簽 67 while(array_shift($sort) != $pre_matches[0][$index][1] && ($count--)) continue; 68 //對剩余HTML標簽進行匹配,若下一個為前綴(p),則向下一層,$deeper加1, 69 //否則后退一層,$deeper減1,$deeper為0則命中匹配結束標記,計算div長度 70 foreach($sort as $key){ 71 if($htmltags[$key] == 'p') { //進入子層 72 $deeper++; 73 }else if($deeper == 0) { //碰到結束標記 74 $length = $key-$pre_matches[0][$index][1]; //長度等於結束標記index 減去 前綴index 75 break; 76 }else { //碰到子層結束標記 77 $deeper--; 78 } 79 } 80 $hitTagStrings[] = substr($data,$pre_matches[0][$index][1],$length).$endTag; 81 break; 82 } 83 } 84 //若只獲取第一個匹配項,退出循環 85 if($first && count($hitTagStrings) == 1) break; 86 } 87 88 return $hitTagStrings; 89 } 90 91 $tag_id = urldecode($_POST['tag_id']); 92 $url = urldecode($_POST['url']); 93 $tag = isset($_POST['tag'])? urldecode($_POST['tag']) : 'div'; 94 $data = urldecode($_POST['data']); 95 $first = (urldecode($_POST['first']) == 'checked')? true : false; 96 foreach($_POST as $key => $value){ 97 if($value == 'EmPtYValue') $$key = false; 98 } 99 echo json_encode(getWebTag($tag_id,$url,$tag,$data,$first)); 100 101 //End_php
注:phpQuery類似jQuery語法實現,非常簡便。