javascript - PHP jQuery :Convert HTML to JSON from given url and create a tree view of html elements

标签 javascript php jquery html json

基本上我有一个文本框,我将在其中输入 URL 并单击“确定按钮”,它将在页面左侧显示 HTML 预览;右侧将有一个在 HTML 中用作附加图像的 HTML 标记(正文、标题、div、span 等)的树形 View 。预期的 JSON 结果应该作为这个问题的结尾。我无法遍历 JSON 并创建树。我尝试了以下方法:

HTML 和 JS 代码:

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ABC</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<body>
<div id="wrapper">
    <header>
        <h1 class="logo"><img src="images/logo.png" alt="" title="" /></h1>
    </header>
    <div id="container">
        <div class="search-box">
            <input type="text" id="url" value="" class="txt-box" />
            <input type="button" value="OK" class="btn-search" />
        </div>
        <div class="inner-wrap">
            <div class="left-wrap" id="preview-sec">

            </div>
            <div class="right-wrap" id="tree-sec">

            </div>
        </div>
    </div>    
</div>

<script type="text/javascript" language="javascript" src="js/jquery-1.11.1.js"></script><!-- Jquery plugin -->
<script>
var counter = 0;
$(document).ready(function(){
    $('.btn-search').click(function(){
        if ($('#url').val() != '') {
            $.get(
                'http://localhost/test/getHTML.php', {url:$('#url').val()},
                function(response) {
                    $('#preview-sec').html(response);
            },'html');
            $.getJSON('http://localhost/test/results.json', function(json) {    
                traverse(json,0);               
            });
        }
    });
});
function traverse(obj,id){
    if (typeof(obj)=="object") {
        if (id == 0) {
            $('#tree-sec').append('<ul></ul>');
        } else {
            $(id).append('<ul></ul>');
        }
        $.each(obj, function(i,val){
            if (i != 'attributes' && i != 'value') {
                counter += 1;
                var li_populate = "<li id="+i+"-"+counter+">"+i+"</li>"; 
                if (id == 0) {
                    $('#tree-sec ul').append(li_populate);
                } else {
                    $(id).find('ul').append(li_populate);
                }
                traverse(val,"#"+i+"-"+counter);
            }
        })
    }
}
</script>
</body>
</html>

PHP 代码:

<?php
    $url = $_GET['url'];
    $html = file_get_contents($url);
    function html_to_obj($html) {
        $dom = new DOMDocument();
        $dom->loadHTML($html);
        return element_to_obj($dom->documentElement);
    }

    function element_to_obj($element) {
        //print_r($element);
        $obj = array();
        $attr = array();
        $arr = array();
        $name = $element->tagName;
        foreach ($element->attributes as $attribute) {
            $attr[$attribute->name] = $attribute->value;
            if ($attribute->name == 'id') {
                $name .= '#'.$attribute->value;
            }
        }
        if (!empty($attr)) {
            $arr["attributes"] = $attr;
        }
        if ($element->nodeValue != '') {
            $arr["value"] = $element->nodeValue;
        }

        foreach ($element->childNodes as $subElement) {         
            if ($subElement->nodeType == XML_TEXT_NODE) {

            }
            elseif ($subElement->nodeType == XML_CDATA_SECTION_NODE) {

            }
            else {
                $arr["child_nodes"][] = element_to_obj($subElement);
            }
        }
        $obj[$name] = $arr;
        return $obj;
    }
    $json = json_encode(html_to_obj($html));
    $fp = fopen('results.json', 'w');
    fwrite($fp,$json);
    fclose($fp);
    echo $html;exit();
?>

JSON 树输出:

enter image description here

JSON 结果:

    {
    "html": {
        "attributes": {
            "lang": "en"
        },
        "value": "Test Development Test\r\n            *{\r\n                box-sizing:border-box;\r\n            }\r\n            body {\r\n                margin:0;\r\n                font-family: sans-serif;\r\n                color: #999;\r\n            }\r\n            a, a:visited {\r\n                text-decoration:none;\r\n            }\r\n            .movie-list .movie{\r\n                width:250px;\r\n                float:left;\r\n                margin-right:25px;\r\n            }\r\n            .movie-list .movie img{\r\n                width:100%;\r\n            }\r\n            .movie-list .movie a.title{\r\n                text-decoration:none;\r\n                color:#999;\r\n                font-weight:bold;\r\n                font-size:18px;\r\n                line-height:25px;\r\n            }\r\n            .movie-list .movie .synopsis{\r\n                font-size:14px;\r\n                line-height:20px;\r\n            }\r\n",
        "child_nodes": {
            "head": {
                "child_nodes": {
                    "meta": {
                        "attributes": {
                            "name": "description",
                            "content": "A ast of animated movies"
                        }
                    },
                    "title": {
                        "value": "Test Development Test"
                    },
                    "style": {
                        "attributes": {
                            "type": "text/css"
                        },
                        "value": "\r\n            *{\r\n                box-sizing:border-box;\r\n            }\r\n            body {\r\n                margin:0;\r\n                font-family: sans-serif;\r\n                color: #999;\r\n            }\r\n            a, a:visited {\r\n                text-decoration:none;\r\n            }\r\n            .movie-list .movie{\r\n                width:250px;\r\n                float:left;\r\n                margin-right:25px;\r\n            }\r\n            .movie-list .movie img{\r\n                width:100%;\r\n            }\r\n            .movie-list .movie a.title{\r\n                text-decoration:none;\r\n                color:#999;\r\n                font-weight:bold;\r\n                font-size:18px;\r\n                line-height:25px;\r\n            }\r\n            .movie-list .movie .synopsis{\r\n                font-size:14px;\r\n                line-height:20px;\r\n            }\r\n"
                    }
                }
            },
            "body": {
                "child_nodes": {
                    "h1": {
                        "value": "List of animated movies"
                    },
                    "div": {
                        "attributes": {
                            "class": "movie-list"
                        },
                        "child_nodes": {
                            "div#bh_6": {
                                "attributes": {
                                    "class": "movie",
                                    "id": "bh_6",
                                    "data-year": "2014"
                                },
                                "child_nodes": {
                                    "img": {
                                        "attributes": {
                                            "src": "http://ia.media-imdb.com/images/M/MV5BMjI4MTIzODU2NV5BMl5BanBnXkFtZTgwMjE0NDAwMjE@._V1_SY317_CR0,0,214,317_AL_.jpg"
                                        }
                                    },
                                    "a": {
                                        "attributes": {
                                            "class": "title",
                                            "href": "http://www.imdb.com/title/tt2245084/"
                                        },
                                        "value": "Big Hero 6"
                                    },
                                    "div": {
                                        "attributes": {
                                            "class": "synopsis"
                                        },
                                        "value": "The special bond that develops between plus-sized inflatable robot Baymax, and prodigy Hiro Hamada, who team up with a group of friends to form a band of high-tech heroes."
                                    }
                                }
                            },
                            "div#tlm": {
                                "attributes": {
                                    "class": "movie",
                                    "id": "tlm",
                                    "data-year": "2014"
                                },
                                "child_nodes": {
                                    "img": {
                                        "attributes": {
                                            "src": "http://ia.media-imdb.com/images/M/MV5BMTg4MDk1ODExN15BMl5BanBnXkFtZTgwNzIyNjg3MDE@._V1_SX214_AL_.jpg"
                                        }
                                    },
                                    "a": {
                                        "attributes": {
                                            "class": "title",
                                            "href": "http://www.imdb.com/title/tt1490017/"
                                        },
                                        "value": "The Lego Movie"
                                    },
                                    "div": {
                                        "attributes": {
                                            "class": "synopsis"
                                        },
                                        "value": "An ordinary Lego construction worker, thought to be the prophesied 'Special', is recruited to join a quest to stop an evil tyrant from gluing the Lego universe into eternal stasis."
                                    }
                                }
                            },
                            "div#httyd": {
                                "attributes": {
                                    "class": "movie",
                                    "id": "httyd",
                                    "data-year": "2010"
                                },
                                "child_nodes": {
                                    "img": {
                                        "attributes": {
                                            "src": "http://ia.media-imdb.com/images/M/MV5BMjA5NDQyMjc2NF5BMl5BanBnXkFtZTcwMjg5ODcyMw@@._V1_SX214_AL_.jpg"
                                        }
                                    },
                                    "a": {
                                        "attributes": {
                                            "class": "title",
                                            "href": "http://www.imdb.com/title/tt0892769/"
                                        },
                                        "value": "How to Train Your Dragon"
                                    },
                                    "div": {
                                        "attributes": {
                                            "class": "synopsis"
                                        },
                                        "value": "A hapless young Viking who aspires to hunt dragons becomes the unlikely friend of a young dragon himself, and learns there may be more to the creatures than he assumed."
                                    }
                                }
                            },
                            "div#up": {
                                "attributes": {
                                    "class": "movie",
                                    "id": "up",
                                    "data-year": "2009"
                                },
                                "child_nodes": {
                                    "img": {
                                        "attributes": {
                                            "src": "http://ia.media-imdb.com/images/M/MV5BMTk3NDE2NzI4NF5BMl5BanBnXkFtZTgwNzE1MzEyMTE@._V1_SX214_AL_.jpg"
                                        }
                                    },
                                    "a": {
                                        "attributes": {
                                            "class": "title",
                                            "href": "http://www.imdb.com/title/tt1049413/"
                                        },
                                        "value": "Up"
                                    },
                                    "div": {
                                        "attributes": {
                                            "class": "synopsis"
                                        },
                                        "value": "By tying thousands of balloons to his home, 78-year-old Carl sets out to fulfill his lifelong dream to see the wilds of South America. Russell, a wilderness explorer 70 years younger, inadvertently becomes a stowaway."
                                    }
                                }
                            },
                            "div#mi": {
                                "attributes": {
                                    "class": "movie",
                                    "id": "mi",
                                    "data-year": "2001"
                                },
                                "child_nodes": {
                                    "img": {
                                        "attributes": {
                                            "src": "http://ia.media-imdb.com/images/M/MV5BMTY1NTI0ODUyOF5BMl5BanBnXkFtZTgwNTEyNjQ0MDE@._V1_SX214_AL_.jpg"
                                        }
                                    },
                                    "a": {
                                        "attributes": {
                                            "class": "title",
                                            "href": "http://www.imdb.com/title/tt0198781/"
                                        },
                                        "value": "Monsters, Inc."
                                    },
                                    "div": {
                                        "attributes": {
                                            "class": "synopsis"
                                        },
                                        "value": "Monsters generate their city's power by scaring children, but they are terribly afraid themselves of being contaminated by children, so when one enters Monstropolis, top scarer Sulley finds his world disrupted."
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

最佳答案

根据您的问题,您遍历返回的 json 对象并创建树的部分存在问题。在您的代码中,用于遍历 json 数据的递归函数在生成 ul 代码时存在一些小问题。返回对象的结构使它有点挑战。

我能够稍微修改您的 html/javascript 代码(无需过多更改)以打印出树。相关代码如下:

CSS:

div#tree-sec ul ul{
    margin-left: 25px;
}
div#tree-sec ul li{
    color: #666;
}
div#tree-sec ul a{
    color: #111;
    text-decoration: underline;
    cursor: pointer;
}   
div#tree-sec ul a:hover {
    text-decoration: none;
}
div#tree-sec ul.collapsible{
    /* Custom parent styles here... */
    /* Such as a folder icon or 'plus' sign */
}

HTML 和 JS:

...
...
<div class="inner-wrap">
    <div class="left-wrap" id="preview-sec">
        <iframe id="preview"></iframe>
    </div>
    <div class="right-wrap" id="tree-sec">
        <ul id="treehtml1"></ul>
    </div>
</div>
....
....
<script type="text/javascript">
    var counter = 0;
    $(document).ready(function(){
        $('.btn-search').click(function(){
            if ($('#url').val() != '') {
                $.get('http://localhost/test/getHTML.php', {url:$('#url').val()}, function(response) {
                    $('#preview-sec').html(response);
                },'html');
                $.getJSON('http://localhost/test/results.json', function(json) {    
                    if(typeof(json) == "object"){
                        traverse(json,'html',1);  
                        makeCollapsible();             
                    }
                });
             }
         });
     });

     function traverse(obj, element, counter){
         for (var i in obj){
             $("#tree"+element+counter).append("<li id='"+i+counter+"'>"+i+"</li>"); // Add element to the tree
             if(obj[i].hasOwnProperty('child_nodes')){
                 $("#"+i+counter).append("<ul id='tree"+i+(counter+1)+"'></ul>"); // If there are children, add a parent ul and pass the name to subsequent recursive calls for each child
                 for(var j in obj[i].child_nodes){
                     traverse(obj[i].child_nodes[j], i, counter + 1); // Recursive call to add child
                 }
             }
          }
      }

      function makeCollapsible(){
          $('ul.parent').each(function(i) {
              var parent_li = $(this).parent('li');
              parent_li.addClass('collapsible'); //Use this selector to style your parent items...

              // Temporarily remove the list from the
              // parent list item, wrap the remaining
              // text in an anchor, then reattach it.
              var sub_ul = $(this).remove();
              parent_li.wrapInner('<a/>').children('a').click(function() {
                 // Toggle the children...
                 sub_ul.toggle();
              });
              parent_li.append(sub_ul);
          });

          // Hide all lists except the outermost.
          $('ul ul').hide();
      }
</script>
....
....

这应该提供一个正确嵌套的基于 ul 的树。如果创建树的图像是一项硬性要求,最好的办法是正确设置生成的 ul 代码片段的样式,在服务器上用它创建一个 html 页面,然后使用服务器端工具如wkhtmltoimage from the wkhtmltopdf package可用于将 html 文档呈现为图像。

另外,我想提到的另一件事是,与其将检索到的 html 加载到 div 中,我建议您使用 iframe 那样,检索到的 html 不会干扰您当前的页面。在上面的示例中,我在预览 div 中添加了一个 iframe。在这种情况下,您可以使用 php 仅输出 json 数据并设置 iframe 以预览 url 就像将 url 分配为 一样简单iframe 的 src 属性。像这样:$("#preview").prop("src", $("#url").val()).

编辑: 更新了代码并进行了修复。还添加了一个新的 js 函数 makeCollapsible() 以根据 OP 的注释将 ul 追溯转换为可点击、可折叠的树结构。还添加了相关的 CSS 样式来设置树结构的样式。对我来说,树现在看起来如下图所示:

Collapsible, Clickable HTML Tree!

关于javascript - PHP jQuery :Convert HTML to JSON from given url and create a tree view of html elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29247235/

相关文章:

javascript - 更新模板内的文本

javascript - 在php服务器端使用js验证安全吗?

javascript - Vue.js 组件图像空白

javascript - 使用 AJAX/PHP 让 HTML 按钮将数据插入 MySQL 数据库

javascript - 如何在屏幕上显示另一个 div 时隐藏一个 div。

javascript - 镜像播放视频作为背景而不使用双缓冲?

php - API Platform v1.1.1 & Symfony 3.2.8 composer 冲突

php - 从登录的社交网络获取访客姓名

javascript - Ruby on Rails 中的可点击表行

jquery - 选择一个元素时禁用其他组