PHP修改网页源代码中的class属性值
下面的代码给网页源代码中的class属性值添加新的随机class属性值,同时如果元素没有id属性,则给元素添加id属性。
<?php
$html = file_get_contents('https://www.ggdoc.cn/');
// 如果输出的页面乱码,需要添加以下代码
$html = mb_convert_encoding($html,'HTML-ENTITIES','utf-8');
var_dump($html);
$result = update_html_class_id($html, 1, '', 3, 'xxx', 2);
var_dump($result);
function update_html_class_id($html, $tag_weapp = 1, $class_prefix = '', $class_type = '', $id_prefix = '', $id_type = '')
{
if (empty($html)) {
return $html;
}
$dom = new DomDocument();
libxml_use_internal_errors(true);
if (!$dom->loadHTML($html)) {
return $html;
}
$dom->preserveWhiteSpace = false;
$content = $dom->getElementsByTagName('*');
foreach ($content as $i => $each) {
if ($each->hasAttribute('class')) {
$class = $each->getAttribute('class');
$new_class = get_class_id($i, $tag_weapp, $class_prefix, $class_type);
$each->setAttribute('class', trim($class . ' ' . $new_class));
if (!$each->hasAttribute('id')) {
$new_id = get_class_id($i, $tag_weapp, $id_prefix, $id_type);
$each->setAttribute('id',$new_id);
}
}
}
$html = $dom->saveHTML($dom->documentElement);
libxml_clear_errors();
return $html;
}
/**
* 获取随机类名和class名
* @param $key
* @param $tag_weapp
* @param $prefix
* @param $type
* @return string
*/
function get_class_id($key = '', $tag_weapp = 1, $prefix = '', $type = '')
{
$key .= $type . $prefix;
if ($tag_weapp == 2) {
$key .= time() . mt_rand(1, 99999);
}
if (empty($prefix)) {
$name = '';
} else {
$name = $prefix . '-';
}
$key = md5($key);
switch ($type) {
case 1:
$name .= substr($key, 0, 10);
break;
case 2:
$name .= substr($key, 0, 4) . '-' . substr($key, 4, 4) . '-' . substr($key, 8, 4) . substr($key, 12, 4);
break;
case 3:
$name .= substr($key, 0, 4) . '-' . substr($key, 4, 4) . '-' . substr($key, 8, 4);
break;
case 4:
$name .= substr($key, 0, 4) . '-' . substr($key, 4, 4);
break;
}
return $name;
}