本文目錄一覽:
php怎麼獲取遠程頁面中的一個div的內容
獲取遠程頁面可以用file_get_contents()函數或者curl拓展,後者的效率會更好,但需要你修改一些配置。
查找html頁面中的內容或者用phpQuery或這個:
或者用php原生的:
或者用正則。
php如何獲取一個網頁中,指定某個div塊的內容
simple_html_dom這個通過篩選CLASS是可以獲得的,但是速度較慢。建議自己通過正則表達式確定想要或取的div塊。
php抓取div內容
?php
$text = file_get_contents(”);
preg_match_all(‘/div id=”hp_text” class=”largeText”([^\/div]+)\/div/’, $text, $arr);
var_dump($arr[1]);
?
輸出:
array (size=1)
0 = string ‘有那麼個地方,曾經讓你想逃;有那麼個地方,生活過才知曉;有那麼個地方,聽別人講起你會心懷驕傲;有那麼個地方,一直是你心底的寶。’ (length=189)
PHP html正則提取div數據
正則提取div數據主要是使用PHP的file_get_content()函數。
具體示例:
HTML代碼:
div class=”chartInfo”
div class=”line”/div
div class=”tideTable”
strong潮汐表/strong數據僅供參考
table width=”500″ border=”0″ cellspacing=”0″ cellpadding=”0″
tbodytr
td width=”100″pspan潮時 (Hrs)/span/p/td
td width=”100″p00:58/p/td
td width=”100″p05:20/p/td
td width=”100″p13:28/p/td
td width=”100″p21:15/p/td
/tr
tr
tdpspan潮高 (cm)/span/p/td
td width=”100″p161/p/td
td width=”100″p75/p/td
td width=”100″p288/p/td
td width=”100″p127/p/td
/tr
/tbody/table
h2時區:-1000 (東10區) 潮高基準面:在平均海平面下174CM/h2
/div
div class=”chart”
/div
/div
首頁先用file_get_content或curl獲取內容部分
PHP的正則處理程序:
?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec( $ch );
curl_close( $ch );
$regex4=”/div class=\”tideTable\”.*?.*?\/div/ism”;
if(preg_match_all($regex4, $return, $matches)){
print_r($matches);
}else{
echo ‘0’;
}
?
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/306561.html