文章詳情頁(yè)
php基于DOMDocument操作頁(yè)面元素實(shí)例 原創(chuàng)
瀏覽:17日期:2022-06-14 08:05:01
問(wèn)題
有如下代碼,要求不使用正則表達(dá)式的情況下修改鏈接為 https://www.jb51.net/softs/
<p>歡迎訪問(wèn)<span>好吧啦網(wǎng)</span> <a Content-Type: text/html; charset=utf-8');// 原始HTML代碼$cont = '<p>歡迎訪問(wèn)<span>好吧啦網(wǎng)</span><a ;// 創(chuàng)建DOMDocument對(duì)象$dom = new DOMDocument();//$dom->encoding = 'UTF-8';//@$dom->loadHTML($cont,LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);@$dom->loadHTML(mb_convert_encoding($cont, 'HTML-ENTITIES','UTF-8'),LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);$aElem = $dom->getElementsByTagName('a');$aElem[0]->setAttribute('href','https://www.jb51.net/softs/');// 給a鏈接添加rel='nofollow'屬性$aElem[0]->setAttribute('rel','nofollow');$content = $dom->saveHTML();//$content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');// 輸出修改后的HTML代碼echo $content;?>運(yùn)行上述代碼,則頁(yè)面源碼即被修改為:
<p>歡迎訪問(wèn)<span>好吧啦網(wǎng)</span><a rel='nofollow'>軟件下載</a></p>這里要注意:loadHTML載入html文本的時(shí)候,需要指定編碼,筆者這里使用的是mb_convert_encoding($cont, 'HTML-ENTITIES','UTF-8') 進(jìn)行編碼轉(zhuǎn)換,另外筆者所測(cè)試網(wǎng)上搜索到的$dom->encoding = 'UTF-8'; 以及 $content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');???均未起到作用。
補(bǔ)充此外,修改元素innerHtml屬性也很簡(jiǎn)單,只需要設(shè)置其nodeValue值即可,上述示例繼續(xù)擴(kuò)展如下:
<?phpheader('Content-Type: text/html; charset=utf-8');//echo $codeid = date('YmdHis').mt_rand(1000,9999);// 原始HTML代碼$cont = '<p>歡迎訪問(wèn)<span>好吧啦網(wǎng)</span><a ;// 創(chuàng)建DOMDocument對(duì)象$dom = new DOMDocument();//$dom->encoding = 'UTF-8';//@$dom->loadHTML($cont,LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);@$dom->loadHTML(mb_convert_encoding($cont, 'HTML-ENTITIES','UTF-8'),LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);$aElem = $dom->getElementsByTagName('a');$aElem[0]->setAttribute('href','https://www.jb51.net/softs/');// 給a鏈接添加rel='nofollow'屬性$aElem[0]->setAttribute('rel','nofollow');//修改span元素的innerHtml值$spanElem = $dom->getElementsByTagName('span');$spanElem[0]->nodeValue = '【好吧啦網(wǎng)軟件下載】===>';$content = $dom->saveHTML();//$content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');// 輸出修改后的HTML代碼echo $content;?>此時(shí)再次訪問(wèn),頁(yè)面元素就變成了:
<p>歡迎訪問(wèn)<span>【好吧啦網(wǎng)軟件下載】===></span><a rel='nofollow'>軟件下載</a></p> 標(biāo)簽:
PHP
相關(guān)文章:
1. PHP腳本的10個(gè)技巧(8)2. PHP中file_get_contents設(shè)置header請(qǐng)求頭,curl傳輸選項(xiàng)參數(shù)詳解說(shuō)明3. PHP循環(huán)與分支知識(shí)點(diǎn)梳理4. ThinkPHP5 通過(guò)ajax插入圖片并實(shí)時(shí)顯示(完整代碼)5. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算6. PHP數(shù)組實(shí)際占用內(nèi)存大小原理解析7. PHP字符串前后字符或空格刪除方法介紹8. 詳解PHP中數(shù)組函數(shù)的知識(shí)點(diǎn)9. php redis setnx分布式鎖簡(jiǎn)單原理解析10. PHP基于phpqrcode類生成二維碼的方法示例詳解
排行榜
