文章詳情頁
php基于DOMDocument操作頁面元素實例 原創
瀏覽:8日期:2022-06-14 08:05:01
問題
有如下代碼,要求不使用正則表達式的情況下修改鏈接為 https://www.jb51.net/softs/
<p>歡迎訪問<span>好吧啦網</span> <a Content-Type: text/html; charset=utf-8');// 原始HTML代碼$cont = '<p>歡迎訪問<span>好吧啦網</span><a ;// 創建DOMDocument對象$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;?>運行上述代碼,則頁面源碼即被修改為:
<p>歡迎訪問<span>好吧啦網</span><a rel='nofollow'>軟件下載</a></p>這里要注意:loadHTML載入html文本的時候,需要指定編碼,筆者這里使用的是mb_convert_encoding($cont, 'HTML-ENTITIES','UTF-8') 進行編碼轉換,另外筆者所測試網上搜索到的$dom->encoding = 'UTF-8'; 以及 $content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');???均未起到作用。
補充此外,修改元素innerHtml屬性也很簡單,只需要設置其nodeValue值即可,上述示例繼續擴展如下:
<?phpheader('Content-Type: text/html; charset=utf-8');//echo $codeid = date('YmdHis').mt_rand(1000,9999);// 原始HTML代碼$cont = '<p>歡迎訪問<span>好吧啦網</span><a ;// 創建DOMDocument對象$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 = '【好吧啦網軟件下載】===>';$content = $dom->saveHTML();//$content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');// 輸出修改后的HTML代碼echo $content;?>此時再次訪問,頁面元素就變成了:
<p>歡迎訪問<span>【好吧啦網軟件下載】===></span><a rel='nofollow'>軟件下載</a></p> 標簽:
PHP
相關文章:
排行榜