Adding attr tag in html via PHP

51 views Asked by At

I would like to add another property and value into my HTML object, but instead, it's replacing the current value.

This is what I've coded so far in my PHP file.

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;
}

but when I run the code

echo json_encode($attr->nodeName);

I get the two attributes:

"class" "aria-label"

2

There are 2 answers

0
Rohit.007 On BEST ANSWER

Try the below code. Changes done:

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;     
                }
             }

Complete code:

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;
}
2
Jorge On

Try adding a new line

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