通过PHP在HTML中添加attr标记

时间:2018-06-26 17:42:15

标签: php html html-object

我想在我的HTML对象中添加另一个属性和值, 而是代替了当前值。

这是我到目前为止在PHP文件中编写的代码。

function htmlEncode ( $html ){

$html = preg_replace('~>\s+<~', '><', $html);
$html = html_entity_decode($html);

$dom = new DOMDocument();
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('*') as $div){

    foreach ($div->attributes as $attr) {

        if($div->nodeName == "h2"){
            $class = $attr->nodeName;
            $className = $attr->nodeValue;
            $div->setAttribute("aria-label", $div->nodeValue);  

            $result = [
                 "tagName" => $div->nodeName, 
                 "value" => $div->nodeValue, 
                 $class=> $className, 
                 $attr->nodeName => $attr->nodeValue
            ];
        } else {
            $result[] = [
                 "tagName" => $div->nodeName, 
                 "value" => $div->nodeValue,
                 $attr->nodeName => $attr->nodeValue
           ];
        }
    }       
}

$json = json_encode($result, JSON_UNESCAPED_UNICODE);

return $json;
}

但是当我运行代码时

echo json_encode($attr->nodeName);

我得到两个属性:

“类别”“ aria-标签”

2 个答案:

答案 0 :(得分:0)

尝试添加新行

$div->setAttribute("class", $div->nodeValue);
$div->setAttribute("aria-label", $div->nodeValue);

答案 1 :(得分:0)

尝试以下代码。 完成的更改:

1. $class[] = array();

2. $class[$attr->nodeName] = $attr->nodeValue;
3. Removed `class` from results
4. Added 
            foreach($class as $key=>$classValues){
                if(!empty($classValues)){
                     $result[$key] = $classValues;     
                }
             }

完整代码:

function htmlEncode ( $html ){

$html = preg_replace('~>\s+<~', '><', $html);
$html = html_entity_decode($html);

$dom = new DOMDocument();
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('*') as $div){
    $class[] = array();
    foreach ($div->attributes as $attr) {
        if($div->nodeName == "h2"){
            $class[$attr->nodeName] = $attr->nodeValue;
            $div->setAttribute("aria-label", $div->nodeValue);

            $result = [
                 "tagName" => $div->nodeName, 
                 "value" => $div->nodeValue,
                 $attr->nodeName => $attr->nodeValue
            ];
            foreach($class as $key=>$classValues){
                 if(!empty($classValues)){
                        $result[$key] = $classValues;     
                 }
            }
        } else {
            $result[] = [
                 "tagName" => $div->nodeName, 
                 "value" => $div->nodeValue,
                 $attr->nodeName => $attr->nodeValue
           ];
        }
    }       
}

$json = json_encode($result, JSON_UNESCAPED_UNICODE);

return $json;
}