php基于DOMDocument操作页面元素实例 <font color=red>原创</font>

问题

有如下代码,要求不使用正则表达式的情况下修改链接为 https://www.jb51.net/softs/ 

<p>欢迎访问<span></span>
    <a href=\"https://www.jb51.net/\">软件下载</a>
</p>

解决方法

笔者使用了DOMDocument进行操作,实例如下:

<?php
header(\'Content-Type: text/html; charset=utf-8\');
// 原始HTML代码
$cont = \'<p>欢迎访问<span></span><a href=\"https://www.jb51.net/\">软件下载</a></p>\';
// 创建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 href=\"https://www.jb51.net/softs/\" 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值即可,上述示例继续扩展如下:

<?php
header(\'Content-Type: text/html; charset=utf-8\');
//echo $codeid = date(\'YmdHis\').mt_rand(1000,9999);
// 原始HTML代码
$cont = \'<p>欢迎访问<span></span><a href=\"https://www.jb51.net/\">软件下载</a></p>\';
// 创建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>【软件下载】===&gt;</span><a href=\"https://www.jb51.net/softs/\" rel=\"nofollow\">软件下载</a></p>

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容