php基于DOMDocument操作頁面元素實例 原創(chuàng)
問題
有如下代碼,要求不使用正則表達式的情況下修改鏈接為 http://chabaoo.cn/softs/
<p>歡迎訪問<span>腳本之家</span> <a href="http://chabaoo.cn/">軟件下載</a> </p>
解決方法
筆者使用了DOMDocument進行操作,實例如下:
<?php header('Content-Type: text/html; charset=utf-8'); // 原始HTML代碼 $cont = '<p>歡迎訪問<span>腳本之家</span><a href="http://chabaoo.cn/">軟件下載</a></p>'; // 創(chuàng)建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','http://chabaoo.cn/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 href="http://chabaoo.cn/softs/" rel="nofollow">軟件下載</a></p>
這里要注意:loadHTML載入html文本的時候,需要指定編碼,筆者這里使用的是mb_convert_encoding($cont, 'HTML-ENTITIES','UTF-8')
進行編碼轉(zhuǎn)換,另外筆者所測試網(wǎng)上搜索到的$dom->encoding = 'UTF-8';
以及 $content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');
???均未起到作用。
補充
此外,修改元素innerHtml屬性也很簡單,只需要設(shè)置其nodeValue值即可,上述示例繼續(xù)擴展如下:
<?php header('Content-Type: text/html; charset=utf-8'); //echo $codeid = date('YmdHis').mt_rand(1000,9999); // 原始HTML代碼 $cont = '<p>歡迎訪問<span>腳本之家</span><a href="http://chabaoo.cn/">軟件下載</a></p>'; // 創(chuàng)建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','http://chabaoo.cn/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 href="http://chabaoo.cn/softs/" rel="nofollow">軟件下載</a></p>
- PHP使用DOMDocument類生成HTML實例(包含常見標(biāo)簽元素)
- 如何解決php domdocument找不到的問題
- PHP中使用DOMDocument來處理HTML、XML文檔的示例
- PHP讀取XML文件的方法實例總結(jié)【DOMDocument及simplexml方法】
- PHP創(chuàng)建XML的方法示例【基于DOMDocument類及SimpleXMLElement類】
- PHP基于DOMDocument解析和生成xml的方法分析
- PHP 中 DOMDocument保存xml時中文出現(xiàn)亂碼問題的解決方案
- php中DOMDocument簡單用法示例代碼(XML創(chuàng)建、添加、刪除、修改)
- PHP XML操作類DOMDocument
相關(guān)文章
php+html5基于websocket實現(xiàn)聊天室的方法
這篇文章主要介紹了php+html5基于websocket實現(xiàn)聊天室的方法,實例分析了php結(jié)合html5的websocket通訊的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07