How to convert HTML to JSON using PHP?

前端 未结 2 695

I can convert JSON to HTML using JsontoHtml library. Now,I need to convert present HTML to JSON as shown in this site. When looked into the code I found the following script

2条回答
  •  再見小時候
    2020-11-28 12:03

    I assume that your html string is stored in $html variable. So you should do:

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    foreach($dom->getElementsByTagName('*') as $el){
        $result[] = ["type" => $el->tagName, "value" => $el->nodeValue];
    }
    
    $json = json_encode($result, JSON_UNESCAPED_UNICODE);
    

    Note: This algorithm doesn't support parent-child tags and fetch all tags as parent elements and parses all of them in a sorted queue. Of course, you can implement this feature by studying the DOMDocument classes features.

提交回复
热议问题