【问题标题】:Parsing "flat" HTML structure with PHP DOM使用 PHP DOM 解析“平面”HTML 结构
【发布时间】:2014-09-02 13:40:32
【问题描述】:
我正在尝试使用 PHP DOM 来帮助解析我想要转换为 JSON 的 HTML 文件。然而,不幸的是,HTML DOM 相当平坦(我无法改变它)。我所说的扁平是指结构是这样的:
<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>
我需要能够获得<h2> 并将<span> 视为孩子。如果有更好的选择,我还没有完全准备好使用 PHP DOM,it's simply what I found in an answer I came across,所以请随时提出任何建议。我真正需要的是将此 HTML 字符串提供给 JSON,而 PHP DOM 看起来是我迄今为止最好的选择。
【问题讨论】:
标签:
php
json
parsing
dom
html-parsing
【解决方案1】:
$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);