Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解析;“平坦”;用PHP-DOM实现HTML结构_Php_Json_Parsing_Dom_Html Parsing - Fatal编程技术网

解析;“平坦”;用PHP-DOM实现HTML结构

解析;“平坦”;用PHP-DOM实现HTML结构,php,json,parsing,dom,html-parsing,Php,Json,Parsing,Dom,Html Parsing,我正在尝试使用PHPDOM来帮助解析一个HTML文件,我想将其转换为JSON。然而,不幸的是,HTMLDOM是相当平坦的(我没有办法改变这一点)。我所说的平面是指结构如下: <h2>title</h2> <span>child node</span> <span>another child</span> <h2>title</h2> <span>child node</span>

我正在尝试使用PHPDOM来帮助解析一个HTML文件,我想将其转换为JSON。然而,不幸的是,HTMLDOM是相当平坦的(我没有办法改变这一点)。我所说的平面是指结构如下:

<h2>title</h2>
<span>child node</span>
<span>another child</span>
<h2>title</h2>
<span>child node</span>
<span>another child</span>
<h2>title</h2>
<span>child node</span>
<span>another child</span>
标题
子节点
另一个孩子
标题
子节点
另一个孩子
标题
子节点
另一个孩子
我需要能够获得
,并将
视为儿童。如果有更好的选择,我还没有完全准备好使用PHPDOM,所以请随时提出建议。我真正需要的是将这个HTML字符串转换成JSON,PHP DOM看起来是迄今为止我最好的选择。

$XML=query('/HTML/*/node()')作为$I=>$node){
$XML =<<<XML
    <h2>title</h2>
    <span>child node</span>
    <span>another child</span>
    <h2>title</h2>
    <span>child node</span>
    <span>another child</span>
    <h2>title </h2>
    <span>child node</span>
    <span>another child</span>
XML;

    $dom = new DOMDocument;
    $dom->loadHTML($XML);
    $xp = new DOMXPath($dom);

    $new = new DOMDocument;
    $root = $new->createElement('root');

    foreach($xp->query('/html//*/node()') as $i => $node) {
        if ($node->nodeType == XML_TEXT_NODE)
            continue;
        if ($node->nodeName == 'h2') {
            if(isset($current))
                $root->appendChild($current);
            $current = $new->createElement('div');
            $current->appendChild($new->importNode($node, true));
            continue;
        }
        $current->appendChild($new->importNode($node, true));
    }

    $new->appendChild($root);
    $xml2 = simplexml_load_string($new->saveHTML());
    echo json_encode($xml2);
如果($node->nodeType==XML\u TEXT\u node) 持续 如果($node->nodeName=='h2'){ 如果(isset(当前)) $root->appendChild($current); $current=$new->createElement('div'); $current->appendChild($new->importNode($node,true)); 持续 } $current->appendChild($new->importNode($node,true)); } $new->appendChild($root); $xml2=simplexml\u load\u字符串($new->saveHTML()); echo json_编码($xml2);