php – DOMDocument 讀取 html 的屬性與設定屬性
<? $htmlDom = new DOMDocument; //須要添加meta 避免中文亂碼 $html = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . '<div class="aaa">Hellow</div>'; $htmlDom->loadHTML($html); $divlist = $htmlDom->getElementsByTagName("div"); foreach ($divlist as $div) { //取得屬性 $str = $div->getAttribute("class"); //設定屬性 $div->setAttribute("data-add", $str); //裡面的文字: Hellow $value = $div->nodeValue; } //輸出: <div class="aaa" data-add="aaa">Hellow</div> echo $htmlDom->saveHTML(); ?>
參考:
DOMDocument:
http://www.php.net/manual/en/class.domelement.php
DOMElement:
http://www.php.net/manual/en/class.domdocument.php